Java Design Patterns: A Hands-On Experience with Real-World Examples, Third Edition Vaskaran Sarcar download
Java Design Patterns: A Hands-On Experience with Real-World Examples, Third Edition Vaskaran Sarcar download
https://ebookmeta.com/product/java-design-patterns-a-hands-on-
experience-with-real-world-examples-third-edition-vaskaran-
sarcar/
https://ebookmeta.com/product/java-design-patterns-a-hands-on-
experience-with-real-world-examples-3rd-edition-vaskaran-sarcar/
https://ebookmeta.com/product/java-design-patterns-a-tour-
of-23-gang-of-four-design-patterns-in-java-1st-edition-vaskaran-
sarcar/
https://ebookmeta.com/product/simple-and-efficient-programming-
with-c-vaskaran-sarcar/
https://ebookmeta.com/product/bane-s-heart-a-world-
beyond-9-michelle-howard/
Paella Recipes: An Easy Paella Cookbook with Delicious
Spanish Recipes (2nd Edition) Booksumo Press
https://ebookmeta.com/product/paella-recipes-an-easy-paella-
cookbook-with-delicious-spanish-recipes-2nd-edition-booksumo-
press/
https://ebookmeta.com/product/mathematical-models-of-convection-
victor-k-andreev/
https://ebookmeta.com/product/graphene-the-route-to-
commercialisation-1st-edition-james-h-baker-james-tallentire/
https://ebookmeta.com/product/conceptual-integrated-science-3rd-
edition-3e-2019-paul-g-hewitt-suzanne-a-lyons-john-a-suchocki-
jennifer-yeh-hewitt/
The Nanny With The Nice List (Nannies of New York 5)
1st Edition K. Sterling
https://ebookmeta.com/product/the-nanny-with-the-nice-list-
nannies-of-new-york-5-1st-edition-k-sterling/
Vaskaran Sarcar
This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.
The publisher, the authors and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
Prerequisite Knowledge
The target readers for this book are those who are familiar with the
basic language constructs in Java and have an idea about the pure
object-oriented concepts like polymorphism, inheritance, abstraction,
encapsulation, and most importantly, how to compile or run a Java
application in the Eclipse IDE. This book does not invest time in easily
available topics, such as how to install Eclipse on your system, how to
write a “Hello World” program in Java, or how to use an if-else
statement or a while loop. I mentioned that this book was written
using the most basic features so that for most of the programs in this
book, you do not need to be familiar with advanced topics in Java. These
examples are simple and straightforward. I believe that these examples
are written in such a way that even if you are familiar with another
popular language such as C# or C++, you can still easily grasp the
concepts in this book.
Who Is This Book For?
In short, you should read this book if the answer is “yes” to the
following questions:
Are you familiar with basic constructs in Java and object-oriented
concepts like polymorphism, inheritance, abstraction, and
encapsulation?
Do you know how to set up your coding environment?
Do you want to explore the design patterns in Java step by step?
Do you want to explore the GoF design patterns? Are you further
interested in learning about Simple Factory, Null Object, and MVC
patterns?
Do you want to examine how the core constructs of Java work behind
these patterns?
Probably you shouldn’t read this book if the answer is “yes” to
any of the following questions:
Are you absolutely new to Java?
Are you looking for advanced concepts in Java excluding the topics
mentioned previously?
Do you dislike a book that has an emphasis on Q&A sessions?
“I do not like the Windows operating system and Eclipse. I want to
learn and use Java without them.” Is this statement true for you?
“I am already confident about GoF design patterns and other patterns
that you mentioned earlier. I am searching for other patterns.” Is this
statement true for you?
Useful Software
These are the important software/tools I used for this book:
I executed and started testing my programs using Java version 16.0.1
and the Eclipse IDE (version 2021-03 (4.19.0)) in a Windows 10
environment. When I started writing this book, they were the latest
versions. It is a big book and when I finished the initial draft, Eclipse
2021-09 was the latest edition and I kept updating the software.
Before I submitted the final version of the book, I tested the code in
Java 17 (version 17.0.1). We can surely predict that version updates
will come continuously, but these version details should not matter
much to you because I have used the fundamental constructs of Java.
So, I believe that this code should execute smoothly in the upcoming
versions of Java/Eclipse as well.
Anything that is the latest today will be old (or outdated) tomorrow.
But the core constructs (or features) are evergreen. All new features
are built on top of these universal features. So, I like to write code
that is compatible with a wide range of versions using the basic
language constructs. I understand that you may have a different
thought, but I like this approach for various reasons. If you know the
latest features, changing the code to them is easy. But the reverse is
not necessarily true. Take another common example: when you
provide support to your clients and fix code defects in an application,
you cannot use the latest language constructs in almost every case,
because the original product was created with a software version
that is old now.
You can download the Eclipse IDE from
www.eclipse.org/downloads/. You’ll see the page shown in
Figure FM-1.
In short, these diagrams help you understand the code, but to learn
design patterns, neither Papyrus nor Eclipse are mandatory. If you
want to learn more about this reverse engineering process, you can
refer to the following link:
https://wiki.eclipse.org/Java_reverse_engineering
.
Note At the time of writing, all links in this book work and the
information is correct. But these links and policies may change in the
future.
2. Soft skills
3. Object-Oriented Programming
4. Compiler construction.
2. Soft skills
Final Words
I must say that you are an intelligent person. You have chosen a subject
that can assist you throughout your career. If you are a
developer/programmer, you need these concepts. If you are an
architect of a software organization, you need these concepts. If you are
a college student, you need these concepts, not only to score high on
exams but to enter the corporate world. Even if you are a tester who
needs to take care of white-box testing or simply needs to know about
the code paths of a product, these concepts will help you a lot.
This book is designed for you in such a way that upon its
completion, you will have developed an adequate knowledge of the
topic, and most importantly, you’ll know how to proceed further.
Remember that this is just the beginning. As you learn about these
concepts, I suggest you write your own code; only then will you master
this area. There is no shortcut for this. Do you remember Euclid’s reply
to the ruler? If not, let me remind you of his reply: There is no royal
road to geometry. So, study and code. Understand a new concept and
code again. Do not give up when you face challenges. These are the
indicators that you are growing better.
Lastly, I hope that this book can help you and you will value the
effort.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub via the book’s
product page, located at www.apress.com/978-1-4842-7970-0. For
more detailed information, please visit www.apress.com/source-code.
Acknowledgments
At first, I thank the Almighty. I sincerely believe that with HIS blessings
only, I could complete this book. I extend my deepest gratitude and
thanks to the following people.
Ratanlal Sarkar and Manikuntala Sarkar: My dear parents, with
your blessings only, I could complete the work.
Indrani, my wife; Ambika, my daughter; Aryaman, my son:
Sweethearts, I love you all.
Sambaran, my brother: Thank you for your constant
encouragement.
Sekhar, Harsha, Abhimanyu, Carsten: As technical advisors,
whenever I was in need, your support was there. Thank you one more
time.
Sunil Sati, Anupam, Ritesh, Ankit: Sunil is ex-colleague cum senior
who wrote the foreword for the second edition of this book. The others
are my friends and technical advisors. Although this time you were not
involved directly, still I acknowledge your support and help in the
development of Java Design Patterns first edition and second edition.
Celestin, Laura, Aditee: Thanks for giving me another opportunity
to work with you and Apress.
Sherly, Vinoth, Siva Chandran: Thank you for your exceptional
support to beautify my work. Thank you all. Your efforts are
extraordinary.
Table of Contents
Part I: Foundation
Chapter 1:Understanding SOLID Principles
Single Responsibility Principle
Initial Program
Demonstration 1
Output
Analysis
Better Program
Demonstration 2
Output
Open/Closed Principle
Initial Program
Demonstration 3
Output
Analysis
Better Program
Demonstration 4
Output
Analysis
Liskov Substitution Principle
Initial Program
Demonstration 5
Output
Better Program
Demonstration 6
Output
Analysis
Interface Segregation Principle
Initial Program
Demonstration 7
Output
Analysis
Better Program
Demonstration 8
Output
Analysis
Dependency Inversion Principle
Initial Program
Demonstration 9
Output
Analysis
Better Program
Demonstration 10
Output
Analysis
Summary
Chapter 2:Simple Factory Pattern
Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration
Output
Analysis
Q&A Session
Final Comment
Part II: The Gang of Four (GoF) Design Patterns
Chapter 3:Factory Method Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Modified Implementation
Demonstration 2
Output
Analysis
Q&A Session
Chapter 4:Abstract Factory Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Analysis
The Client Code Variations
Demonstration 2
Demonstration 3
Q&A Session
Chapter 5:Prototype Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Modified Implementation
Class Diagram
Demonstration 2
Output
Analysis
Further Improvements
Q&A Session
Shallow Copy vs.Deep Copy
Demonstration 3
Output From Shallow Copy Implementation
Analysis
Output From Deep Copy Implementation
Analysis
Q&A Session Continued
Demonstration 4
Output
Analysis
Chapter 6:Builder Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Q&A Session
Alternative Implementation
Demonstration 2
Output
Analysis
Q&A Session Continued
Chapter 7:Singleton Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Analysis
Q&A Session
Alternative Implementations
Demonstration 2:Eager Initialization
Analysis
Demonstration 3:Bill Pugh’s Solution
Analysis
Demonstration 4:Enum Singleton
Analysis
Q&A Session Continued
Chapter 8:Proxy Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Q&A Session
Demonstration 2
Output
Chapter 9:Decorator Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Using Subclassing
Using Object Composition
Class Diagram
Package Explorer View
Demonstration
Output
Q&A Session
Chapter 10:Adapter Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Analysis
Types of Adapters
Object Adapters
Class Adapters
Q&A Session
Demonstration 2
Output
Analysis
Chapter 11:Facade Pattern
GoF Definition
Concept
Real-World Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration
Output
Analysis
Q&A Session
Chapter 12:Flyweight Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration
Output
Analysis
Q&A Session
Chapter 13:Composite Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration
Output
Analysis
Q&A Session
Chapter 14:Bridge Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Additional Implementation
Class Diagram
Demonstration 2
Output
Q&A Session
Chapter 15:Template Method Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Q&A Session
Demonstration 2
Output
Chapter 16:Observer Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration
Output
Q&A Session
Chapter 17:Chain of Responsibility Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration
Output
Q&A Session
Chapter 18:Iterator Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Additional Comments
Demonstration 2
Output
Q&A Session
Demonstration 3
Output
Chapter 19:Command Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Q&A Session
Modified Implementation
Class Diagram
Demonstration 2
Output
Chapter 20:Memento Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Analysis
Q&A Session
Additional Implementation
Class Diagram
Package Explorer View
Demonstration 2
Output
Analysis
Chapter 21:Strategy Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration
Output
Q&A Session
Chapter 22:State Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration
Output
Analysis
Q&A Session
Chapter 23:Mediator Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Analysis
Additional Implementation
Demonstration 2
Output
Analysis
Q&A Session
Chapter 24:Visitor Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Analysis
Using Visitor Pattern and Composite Pattern Together
Step 1
Step 2
Step 3
Step 4
Step 5
Demonstration 2
Output
Analysis
Demonstration 3
Output
Q&A Session
Chapter 25:Interpreter Pattern
GoF Definition
Concept
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration 1
Output
Analysis
Q&A Session
Alternative Implementation
Demonstration 2
Output
Part III: Additional Design Patterns
Chapter 26:Null Object Pattern
Definition
Concept
A Faulty Program
Output
An Unwanted Input
The Potential Fix
Analysis
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration
Output
Analysis
Q&A Session
Chapter 27:MVC Pattern
Definition
Concept
Key Points to Remember
Variation 1
Variation 2
Variation 3
Real-Life Example
Computer World Example
Implementation
Class Diagram
Package Explorer View
Demonstration
Output
Q&A Session
Modified Output
Analysis
Part IV: The Final Talks on Design Patterns
Chapter 28:Criticisms of Design Patterns
Q&A Session
Chapter 29:Anti-Patterns
Overview
Brief History of Anti-Patterns
Examples of Anti-Patterns
Types of Anti-Patterns
Q&A Session
Chapter 30:FAQ
Appendix A:A Brief Overview of GoF Design Patterns
Q&A Session
Appendix B:The Road Ahead
A Personal Appeal to You
Appendix C:Recommended Reading
Index
About the Author
Vaskaran Sarcar
obtained his Master of Engineering in
software engineering from Jadavpur
University, Kolkata (India) and an MCA
from Vidyasagar University, Midnapore
(India). He was a National Gate Scholar
from 2007-2009 and has more than 12
years of experience in education and the
IT industry. Vaskaran devoted his early
years (2005-2007) to the teaching
profession at various engineering
colleges. Later he joined HP India PPS
R&D Hub Bangalore. He worked there
until August 2019. At the time of his
retirement from HP, he was a Senior
Software Engineer and Team Lead. To
follow his dream and passion, Vaskaran
is now an independent full-time author. Other Apress books by him
include
Simple and Efficient Programming in C# (Apress, 2021)
Design Patterns in C# Second Edition (Apress, 2020)
Getting Started with Advanced C# (Apress, 2020)
Interactive Object-Oriented Programming in Java Second Edition
(Apress, 2019)
Java Design Patterns Second Edition (Apress, 2019)
Design Patterns in C# (Apress, 2018)
Interactive C# (Apress, 2017)
Interactive Object-Oriented Programming in Java(Apress, 2016)
Java Design Patterns (Apress, 2016)
The following list is of his non-Apress books:
Python Bookcamp (Amazon, 2021)
Operating System: Computer Science Interview Series (Createspace,
2014)
About the Technical Reviewers
Abhimanyu
is a self-motivated technological
enthusiast with over 13 years of
experience in software development. He
is an expert in building big data solutions
and large-scale machine learning
applications, especially in the retail
domain. Currently, Abhimanyu is
building data-aware apps and solutions
for the world’s largest retailer.
Along with his work, he also likes
astrophotography, speed-cubing, and
playing his acoustic guitar in his free
time.
Carsten Thomsen
is a back-end developer primarily
working with smaller front-end bits as
well. He has authored and reviewed a
number of books and created numerous
Microsoft Learning courses, all to do
with software development. He works as
freelancer/contractor in various
countries in Europe, using Azure, Visual
Studio, Azure DevOps, and GitHub. Being
an exceptional troubleshooter by asking
the right questions, including the less
logical ones, in a most-logical-to-least-
logical fashion, he also enjoys working
with architecture, research, analysis,
development, testing, and bug fixing.
Carsten is a very good communicator
with great mentoring and team-lead skills, and great skills researching
and presenting new material.
Harsha Jayamanna
has more than seven years of software
engineering experience. Java, Spring,
JakartaEE, Microservices, and Cloud are
several of his expertise areas. He started
his career in Sri Lanka and then, after
several years, moved to Singapore.
Currently, he is working as a software
consultant in Sydney, Australia. Writing
blog articles, reading technical books,
and learning new technologies are his
other areas of interest.He can be reached
via
https://www.harshajayamanna.c
om/.
Java is a powerful object-oriented programming language, and it has many features. If we compare it with
the old days, we must say that coding has become easier with the support of these powerful features. But the
hard truth is that simply using these features in an application does not guarantee that you have used them
in the right way. In any given requirement, it is vital to identify classes, objects, and how they communicate
with each other. In addition, your application must be flexible and extendable to fulfill future enhancements.
This is one of the primary aims of learning design patterns. This is often termed experience reuse because
you earn benefits from other people’s experiences as you go through their struggles and see how they solved
those problems and adopted new behaviors in their systems. A pattern may not perfectly fit into your target
application, but if you know the best practices in advance, you are more likely to make a better application.
Hopefully, you can guess that understanding different design patterns may not be very easy at the
beginning. You need to know certain principles or guidelines before you implement a pattern in your code.
These fundamental guidelines are not only common to all patterns, they are also useful to produce good-
quality software.
In the previous editions of this book, I needed to assume that you knew at least some of them. Whenever
I referred to these principles, either I explained them briefly or I gave you pointers to where you could learn
more. This strategy was helpful to make the book slim.
Now you are holding the third edition of Java Design Patterns . Since you liked the previous edition of this
book, I wanted to start with materials that can make your learning experience easier. So, I start with some
fundamental guidelines that every developer should know before implementing a design pattern. Yes, I
sincerely believe the previous line. Let’s learn some of these guidelines.
Robert Cecil Martin is a famous name in the programming world. He is an American software engineer
and best-selling author and is also known as "Uncle Bob." He promoted many principles. The following is a
subset of them:
Single Responsibility Principle (SRP)
Open/Closed Principle (OCP)
Liskov Substitution Principle (LSP)
Interface Segregation Principle (ISP)
Dependency Inversion Principle (DIP)
Taking the first letter of each principle, Michael Feathers introduced the SOLID acronym to remember
these names easily.
Design principles are high-level guidelines that you can use to make better software. They are not bound
to any particular computer language. So, if you understand these concepts using Java, you can use them with
similar languages like C# or C++. To understand the thoughts of Robert C Martin about this, go to
https://sites.google.com/site/unclebobconsultingllc/getting-a-solid-start,
which says
The SOLID principles are not rules. They are not laws. They are not perfect truths. They are statements
on the order of “An apple a day keeps the doctor away.” This is a good principle, it is good advice, but it’s
not a pure truth, nor is it a rule.
Uncle Bob
In this chapter, you’ll explore these principles in detail. In each case, I start with a program that compiles
and runs successfully, but does not follow any specific design guidelines. In the analysis section, I’ll discuss
the possible drawbacks and try to find a better solution using these principles. This process can help you
understand the importance of these design guidelines. I remind you again: examining these case studies will
help you think better and make better applications, but they are not rules that you must follow in every
context.
Point To Remember
When you follow the SRP, your code is smaller, cleaner, and less fragile. So how do you follow this
principle? A simple answer is you can divide a big problem into smaller chunks based on different
responsibilities and put each of these small parts into separate classes. The next question is, what do we
mean by responsibility? In simple words, responsibility is a reason for a change. In his best-selling
book Clean Architecture (Pearson, 2017), Robert C. Martin warns us not to confuse this principle with the
principle that says a function should do one, and only one, thing. He also says that perhaps the best way to
understand this principle is when you look at the symptoms of violating it.
I also believe the same, not only for this principle but for other principles as well. This is why in the
upcoming discussion you’ll see me first write a program without following these principles. Then I’ll
show you a better program following these principles.
Initial Program
Demonstration 1 has an Employee class with three different methods. Here are the details:
The displayEmpDetail() shows the employee's name and their working experience in years.
The generateEmpId() method generates an employee id using string concatenation. The logic is
simple: I concatenate the first word of the first name with a random number to form an employee ID. In
the following demonstration, inside the main() method (the client code) I create two Employee
instances and use these methods to display the relevant details.
The checkSeniority() method evaluates whether an employee is a senior person. I assume that if the
employee has 5+ years of experience, he is a senior employee; otherwise, he is a junior employee.
Demonstration 1
Here is the complete demonstration. When you download the source code from the Apress website, refer to
package jdp3e.solid_principles.without_srp to get all parts of this program.
// Employee.java
import java.util.Random;
class Employee {
public String firstName, lastName, empId;
public double experienceInYears;
public Employee(String firstName, String lastName,
double experience) {
this.firstName = firstName;
this.lastName = lastName;
this.experienceInYears = experience;
}
// Client.java
class Client {
public static void main(String[] args) {
System.out.println("*** A demo without SRP.***");
System.out.println("\n*******\n");
Note For brevity, I do not include the common package name before each segment of the code. The
same comment applies to all demonstrations in this book.
Output
Here is a sample output. Note that the employee ID can vary in your case because it generates a random
number to get the employee ID.
“Can you tell us, uncle, the names of the greatest warriors who
have ever lived, and of the most famous battles which have ever been
fought?”
“Some of them I can tell you, but my memory must be a great deal
better than it is to tell you a twentieth part of either the great
warriors of the world, or of the great battles they have fought. Great
men and great warriors are sometimes very different things. Were
mankind estimated according to the lives they have taken all
conquerors would be great, but if ranked according to the benefits
they have conferred, many of them would be very little. Among the
ancients, Alexander the Great stands pre-eminent as conqueror;
while, in more modern times, must be reckoned Frederick the Great
of Prussia, Charles XII. of Sweden, Peter the Great of Russia,
Buonaparte of France, and the Duke of Marlborough and the Duke of
Wellington of England.”
“And which are some of the most famous battles?”
“Those that have been most spoken of are, the siege of Troy; the
battle fought on the plains of Marathon, and the fight in the defile of
Thermopylæ; while, in more modern times, may be reckoned the
following among a hundred others; the battle of Hastings, wherein
King Harold was slain; Bannockburn, where the Scotch, under the
renowned Robert Bruce, beat the English under Edward II.; Cressy,
where Edward III. obtained a splendid victory over the French;
Poictiers, where the King of France and his son were taken prisoners;
Agincourt, wherein Henry V. defeated the French. This battle was
fought on St. Crispin’s-day, and our great poet, Shakspeare, thus
alludes to it:—
BATTLE OF AGINCOURT.
“Great as Charles thought himself in the field, Peter the Great was
too much for him at last.”
“Peter the Great of Russia was a most extraordinary man, and a
warrior of no common order. He came over to England and worked
in the dockyard at Deptford as a shipwright, to improve himself in
the building of ships for his navy; he learned the trade of a smith,
and forged a bar of iron at Olaneta in Russia, which weighed a
hundred and twenty pounds. What think you, boys, of a mighty
monarch working as a blacksmith, and making his nobles blow the
bellows for him?”
“There are very few monarchs that would do that.”
“Peter the Great won many battles, but the victory of Pultowa over
his rival in arms, Charles XII. of Sweden, ruined the latter. Peter died
in the fifty-third year of his age, and the great monument at
Petersburgh, erected to his memory, is a prodigious work of art. The
pedestal is a single stone of red granite, weighing more than fourteen
hundred tons. Peter is represented on horseback, crowned with
laurel, and sitting on a housing of bear-skin. The horse, a fiery
courser, stands on his hind feet, as if resolved to arrive at the
pinnacle of the rock.”
“It must be a grand monument, but how the Russians could
contrive to take that big stone to the place where it was to be set up,
is a puzzle.”
“The great Duke of Marlborough was a mighty and successful
warrior. In his grand battle at Blenheim, on the Danube, besides
destroying twelve thousand French and Bavarians he took thirteen
thousand prisoners, and Marshall Tallard among them. It was for
this exploit that Blenheim House, a princely mansion near Oxford,
was given to him, and his heirs. Great as the duke was in military
fame, he at last became childish, and wept when beaten at chess,
saying, ‘Every one can beat me now?’ You see, boys, how little it
becomes us to be proud, for he who is great to-day may be little,
indeed, to-morrow. While I tell you about soldiers and sailors, and of
the reputation that many of them have attained, remember, that to
be a great warrior unennobled by proper motives, is only to be a
great destroyer. Aim at uprightness, usefulness, patriotism, loyalty,
honour, and humanity, and you will then be true friends to your
country.”
CHAPTER VI.
“What a desperate battle it must have been! Have you told us all
about uniforms?”
“Why, I think that you have had quite enough of dress, I will,
therefore, only say, that the rifle regiments wear green jackets and
trousers, with a black beaver cap. The duty of the rifle-corps is
different from that of other soldiers, for they hide themselves behind
the trees, or lie along on the ground, or among the bushes, so as to be
able to pick off the officers of the enemy with their rifles. Their dress
is green, that they may not be spied out so easily. A rifleman will fire
off his piece in almost any attitude, and bring down his enemy.”
“What, do they pick off the officers one by one, just as a sportsman
does his birds?”
“They do, boys! Many practices in war will hardly do to dwell
upon. I have not said so much about the uniform of sailors as of the
uniform of soldiers; but I will give you a droll account of the scrape
that a boatswain once got into on account of his love of finery. I think
the account is given by Captain Hall, but I am not certain.”
“Let us hear it! Let us hear it!”
“I remember once, on the beach of Madras, witnessing an amusing
scene between Sir Samuel Hood, then commander-in-chief in India,
and the newly-promoted boatswain of a sloop-of-war, belonging to
the squadron. The admiral, who was one of the bravest, and kindest,
and truest-hearted seamen that ever trod a ship’s decks, was a sworn
foe to all trickery in dress-work. The eye of the veteran officer was
directed earnestly towards the yeast of waves, which, in immense
double rows of surf, fringe and guard the whole of that flat shore. He
felt more anxious than usual about the fate of this particular boat,
from having ordered on shore the person alluded to, with whom he
wished to have some conversation previously to their parting
company. This boatswain was a young man, who had been for some
years a follower of the admiral, in different ships, and to whom he
had just given a warrant. The poor fellow, unexpectedly promoted
from before the mast to the rank of an officer, was trigged up in his
newly bought but marvellously ill-cut uniform, shining like a dollar,
and making its wearer, who, for the first time in his life, had put on a
long coat, feel not a little awkward.
“As soon as the boat was partly driven up the beach by the surf,
and partly dragged beyond the dash of the breakers by the crowd on
shore, this happiest of warrant-officers leaped out on the sand, and
seeing the admiral above him, standing on the crest of the natural
glacis, which lines the shore, he took off his hat, smoothed down the
hair on his forehead, sailor-fashion, and stood uncovered, in spite of
the roasting sun flaming in the zenith.
“The admiral, of course, made a motion with his hand for the
boatswain to put his hat on, but the other, not perceiving the signal,
stood stock still.
“‘I say, put on your hat!’ called the commander-in-chief, in a tone
which made the newly-created warrant start. In his agitation he
shook a bunch of well trimmed ringlets a little on one side, and
betrayed, to the flashing eyes of the admiral, a pair of small, round,
silver ear-rings, the parting gift, doubtless, of some favoured and
favouring ‘Poll’ or ‘Bess,’ of dear, old blackguard Point Beach, the
very ninth heaven of all lighthearted sailors. Be this as it may, the
admiral, first stepping on one side, and then holding his head
forward, as if to re-establish the doubting evidence of his horrified
senses, and forcibly keeping down the astonished seaman’s hat with
his hand, roared out,
“‘Who are you?’
“‘John Marline, sir!’ replied the bewildered boatswain, beginning
to suspect the scrape he had got himself into.
“‘Oh!’ cried the flag-officer, with a scornful laugh. ‘Oh! I beg your
pardon; I took you for a Portuguese.’
“‘No, sir!’ instinctively faltered out the other, seeing the admiral
expected some reply.
“‘No? Then if you are not a foreigner, why do you hoist false
colours? What business has an English sailor with these trumpery
machines in his ears?’
“‘I don’t know, sir,’ said poor Marline. ‘I put them in only this
morning, when I rigged myself in my new togs, to answer the signal
on shore.’
“‘Then,’ said Sir Samuel, softened by the contrite look of his old
shipmate, and having got rid of the greater portion of his bile by the
first explosion, ‘you will now proceed to unrig yourself of this top
hamper as fast as you can; pitch them into the surf, if you like, but
never, as you respect the warrant in your pocket, let me see you in
that disguise again.’”
CHAPTER VII.
“Can you tell us something about the artillery, uncle? There must
be a great many pieces of cannon used in an army?”
“There are; and if you never know more about them than the
information you get from me, so much the better; better to hear of
them than to be among them. I will say a little about the weapons of
war generally, but can only glance at the subject: it would take me a
week to tell you everything, if I had it all at the tip of my tongue.”
“Well, so that your account is not too short, we must be satisfied.”
“As the world turns round, the weapons in use among soldiers and
sailors and the customs of warfare change.
“When the twang of the bow is heard no more,
Then muskets rattle and cannons roar.
I need not dwell on the clubs, the spears, the bills, and battle-axes of
former times; the slings, the bows and arrows, the cross-bows and
the maces, that were accustomed to deal death around, are unknown
to modern warfare, nor are the scythe-armed chariot, the battering-
ram, the balista, or the catapulta, now ever used in the sea or land
service of Old England.”
“Ay! gunpowder has put them all aside.”
“Artillery does not mean cannon only, but all the huge weapons,
apparatus, and stores used in the field, or in garrisons and sieges. A
train of artillery comprehends cannon, mortars, and howitzers of all
kinds, properly mounted; with horses, carriages, mortar-beds, block-
carriages, ammunition-waggons, stores, shells, shot, bullets, powder,
and cartridges.”
“What a deal of room a train of artillery must take up!”
“Indeed it does, for beside what I have told you, it includes
artificers’ tools, intrenching tools, and miners’ tools, with forges,
capstans and gins, pontoons, pontoon-carriages, tumbrels, chevaux-
de-frise, palisades, drag-ropes, platforms, harness, flints, powder-
measures, fuze-engines, and tents, to say nothing of a hundred other
things that I cannot remember.”
“What is meant by chevaux-de-frise?”
“Chevaux-de-frise are pieces of timber, about ten or a dozen feet
long, stuck all over with wooden pins, six feet long, shod with iron.
They are used to stop up a breach, or a pass, or to secure a camp, and
are sometimes rolled down on the enemy in an assault. The sword,
the musket, the pike, and the bayonet, the cannon, the howitzer, and
the mortar, with granades, rockets, and shells, are the principal
weapons of our present wars. There are some who still entertain the
opinion that bows and arrows in English hands have been more
destructive than muskets bristling with bayonets, and this seems to
me to be very like the truth. The difference between the long-bow
and the cross-bow, is this: the long-bow is only a bow and string, and
its force depends on the power of the arm that draws it. The cross-
bow, is a bow fastened on a stock, so that when it is once drawn
ready to be let off, it has the same power whether let off by a strong
man or a weak one.”
“Why, boys shoot with bows and arrows.”
“They do, but they must be men to draw an arrow to the head on
the string of the long-bow of old times. Topham, one of the strongest
men ever known, laughed to scorn an old archer, who boasted that
he could draw a cloth-yard arrow to the head on the long-bow.
Topham tried to do this, but could only half draw it, while the old
archer, taking up the bow, performed the feat adroitly. But a word as
to the power of the bow. A military man of experience says, ‘The
accuracy and range of the arrow fully equalled the present most
perfect practice of the rifle, and it greatly exceeded it with respect to
rapidity of discharge.’ In the early part of the reign of Henry VIII. it
was still the opprobrium of an archer if he shot a single shaft during
a battle without killing or disabling his enemy. Some have compared
this with Marshal Saxe’s calculations upon the efficacy of the musket.
Marshal Saxe estimated that in no case did more than one ball in
eighty-five take effect, and that at the battle of Tournay, not more
than one half in four hundred was calculated to have killed an
enemy; it must be left to military men to say whether the lead ‘shot
from the deadly level of a gun,’ has been made more deadly since the
tactics of Marshal Saxe. The disuse of the long-bow is hardly to be
accounted for. An archer was deemed disqualified for service if he
could not fire twelve unerring shafts in one minute. This, if we take
the accuracy of their fire, for we must be allowed the term, into
consideration, will make the practice of musketry very inferior.”
“Do you think bows and arrows will ever be used again by
soldiers?”
“I think not, for the archer is not so well provided for close fighting
as he who carries a musket: the ball on the inside, and the bayonet
on the out, render the musket a most formidable weapon.”
“How dreadful it must be to charge with the bayonet! but, indeed,
the sword must be dreadful too.”
“As I have undertaken to answer your questions, and to tell you
about war and warlike weapons, I suppose that you must know all
that I happen to remember. About a dozen years ago Captain Von
Selmnitz projected a new mode of employing the bayonet, and
afterwards paid such attention to it that it became very popular; and
many officers in the service of other countries resorted to Dresden to
study under him. It was thought by many, that under this system a
single foot soldier, of common strength and of moderately good eye
and limb, would be able to resist two horsemen. It was the dexterous
use made of the cudgel among the common people in Brittany and
Normandy, that led Selmnitz to reflect on the matter, and to apply it
to the bayonet.”
“Which is the worst, the bayonet or the sword?”
“There is a difference of opinion respecting swords and bayonets
as weapons of destruction, or, in other words, between the power of
infantry armed with swords, and infantry armed with muskets and
bayonets. An officer describes the bayonet as a rickety, zigzag,
unhandy instrument, and says that, ‘at Preston-Pans two thousand
highlanders, armed only with broad-swords and targets, overthrew,
at the very first onset, nearly two thousand British infantry, and
completed their defeat in about a quarter of an hour. The same was
the case at Falkirk, and even at Culloden: every point of the line that
the highlanders reached in their charge was completely overthrown!
The destruction made by musketry is certainly not so great as we
might expect from so formidable a weapon.’”
“One would think that almost every bullet would kill a man.”
“That is not the case by a great deal, as you shall hear. The same
officer goes on to reason the matter thus: ‘Supposing that twenty
thousand French were killed and wounded at Waterloo, and allowing
five thousand of these to have fallen by the fire of the artillery and
the sabres of the cavalry, it leaves fifteen thousand to the share of the
infantry; and counting the latter at thirty thousand only, though the