100% found this document useful (2 votes)
11 views

Java Design Patterns: A Hands-On Experience with Real-World Examples, Third Edition Vaskaran Sarcar download

The document is about the third edition of 'Java Design Patterns: A Hands-On Experience with Real-World Examples' by Vaskaran Sarcar, which aims to enhance programming skills through the use of design patterns in Java. It outlines the book's organization, including sections on SOLID principles, Gang of Four design patterns, and additional patterns, along with Q&A sessions for deeper understanding. The target audience includes readers familiar with basic Java constructs and object-oriented concepts, while the book emphasizes practical coding examples and accessibility for various Java versions.

Uploaded by

aynethnafkha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
11 views

Java Design Patterns: A Hands-On Experience with Real-World Examples, Third Edition Vaskaran Sarcar download

The document is about the third edition of 'Java Design Patterns: A Hands-On Experience with Real-World Examples' by Vaskaran Sarcar, which aims to enhance programming skills through the use of design patterns in Java. It outlines the book's organization, including sections on SOLID principles, Gang of Four design patterns, and additional patterns, along with Q&A sessions for deeper understanding. The target audience includes readers familiar with basic Java constructs and object-oriented concepts, while the book emphasizes practical coding examples and accessibility for various Java versions.

Uploaded by

aynethnafkha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Java Design Patterns: A Hands-On Experience with

Real-World Examples, Third Edition Vaskaran


Sarcar install download

https://ebookmeta.com/product/java-design-patterns-a-hands-on-
experience-with-real-world-examples-third-edition-vaskaran-
sarcar/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Java Design Patterns: A Hands-On Experience with Real-


World Examples 3rd Edition Vaskaran Sarcar

https://ebookmeta.com/product/java-design-patterns-a-hands-on-
experience-with-real-world-examples-3rd-edition-vaskaran-sarcar/

Java Design Patterns a tour of 23 gang of four design


patterns in Java 1st 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/

Simple and Efficient Programming with C# Vaskaran


Sarcar

https://ebookmeta.com/product/simple-and-efficient-programming-
with-c-vaskaran-sarcar/

Bane s Heart A World Beyond 9 Michelle Howard

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/

Mathematical Models of Convection Victor K. Andreev

https://ebookmeta.com/product/mathematical-models-of-convection-
victor-k-andreev/

Graphene The Route to Commercialisation 1st Edition


James H Baker James Tallentire

https://ebookmeta.com/product/graphene-the-route-to-
commercialisation-1st-edition-james-h-baker-james-tallentire/

Terrorism Criminal Law and Politics The Decline of the


Political Offence Exception to Extradition
Transnational Criminal Justice 1st Edition Julia
Jansson
https://ebookmeta.com/product/terrorism-criminal-law-and-
politics-the-decline-of-the-political-offence-exception-to-
extradition-transnational-criminal-justice-1st-edition-julia-
jansson/

conceptual integrated science 3rd edition 3e 2019 Paul


G. Hewitt & Suzanne A Lyons & John A. Suchocki &
Jennifer Yeh [Hewitt

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

Java Design Patterns


A Hands-On Experience with Real-World Examples
3rd ed.
Vaskaran Sarcar
Garia, Kolkata, India

ISBN 978-1-4842-7970-0 e-ISBN 978-1-4842-7971-7


https://doi.org/10.1007/978-1-4842-7971-7

© Vaskaran Sarcar 2022

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 use of general descriptive names, registered names, trademarks,


service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.

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.

This Apress imprint is published by the registered company APress


Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
First, I dedicate this book to Almighty GOD and the Gang of Four. Then I
dedicate this work to all who have great potential to produce top-quality
software but could not flourish for to various reasons. My message for
them: “Dear reader, I want to hold your hands and help you express your
hidden talents to the outside world.”
Introduction
It is my absolute pleasure to write the third edition of Java Design
Patterns for you. You can surely guess that I got this opportunity
because you liked the previous edition of the book and shared your nice
reviews from across the globe. So, once again I’m excited to join your
design patterns journey. This time I present a further simplified, better
organized, and content-rich edition to you.
You probably know that the concept of design patterns became
extremely popular with the Gang of Four’s famous book Design
Patterns: Elements of Reusable Object-Oriented Software (Addison-
Wesley, 1994). The book came out at the end of 1994, and it primarily
focused on C++. But it is useful to know that these concepts still apply
in today’s programming world. Sun Microsystem released its first
public implementation of Java 1.0 in 1995. So, in 1995, Java was new to
the programming world. Since then, it has become rich with new
features and is now a popular programming language. On the other
hand, the concepts of design patterns are universal. So, when you
exercise these fundamental concepts of design patterns with Java, you
open new opportunities for yourself.
My end goal is simple: I want you to develop your programming
skills to the next level using design patterns in your code.
Unfortunately, this skill set cannot be acquired simply by reading. This
is why I made this guide to the design patterns that you want to use in
Java.
I have been writing books on design patterns since 2015 in different
languages such as Java and C#. These books were further enhanced,
and multiple editions of them were published and well received. In the
initial version, my core intention was to implement each of the 23 Gang
of Four (GoF) design patterns using simple examples. One thing was
always in my mind when writing: I wanted to use the most basic
constructs of Java so that the code would be compatible with both the
upcoming version and the legacy version of Java. I have found this
method helpful in the world of programming.
In the last few years, I have received many constructive suggestions
from my readers. The second edition of this book was created with that
feedback in mind. I also updated the formatting and corrected some
typos from the previous version of the book and added new content to
this edition. In the second edition of the book, I focused on another
important area. I call it the “doubt-clearing sessions.” I knew that if I
could add some more information such as alternative ways to write
these implementations, the pros and cons of these patterns, and when
to choose one approach over another, readers would find this book
even more helpful. So, in the second edition of the book, “Q&A Session”
sections were added in each chapter to help you learn each pattern in
more depth. I know you liked it very much.
So, what is new in the third edition? Well, the first thing I want to
tell you is that since the second edition of the book is already big, this
time I made the examples shorter and simpler. Also, I place the related
chapters close to each other. This is why you’ll see the Chain of
Responsibility pattern after the Observer pattern. The same is true for
Simple Factory and Factory Method patterns, Strategy and State
patterns, and Command and Memento patterns. In addition, at the
beginning of the book, you’ll read a detailed discussion on SOLID design
principles, which are used heavily across these patterns. Apart from
these changes, I add more code explanations for your easy
understanding.
Malcolm Gladwell in his book Outliers (Little, Brown and Company,
2008) talked about the 10,000-hour rule. This rule says that the key to
achieve world-class expertise in any skill is, to a large extent, a matter
of practicing the correct way for a total of around 10,000 hours. I
acknowledge the fact that it is impossible to consider all experiences
before you write a program. Sometimes, it is also ok to bend the rules if
the return on investment (ROI) is nice. So, I remind you about the
Pareto principle or the 80-20 rule. This rule simply states that 80% of
outcomes come from 20% of all causes. This is useful in programming,
too. When you identify the most important and commonly used design
patterns and use them in your applications properly, you can make top-
quality programs. In this book, I discuss the programming patterns that
can help you write better programs. You may know some of them
already, but when you see them in action and go through the Q&A
sessions, you’ll understand their importance.
How the Book Is Organized
The book has four major parts:
Part 1 consists of the first two chapters, in which you will explore the
SOLID principles and learn to use the Simple Factory pattern.
Part 2 consists of the next 23 chapters, in which you learn and
implement all of the Gang of Four design patterns.
In the world of programming, there is no shortage of patterns, and
each has its own significance. So, in addition to the SOLID principles
and design patterns covered in Part 1 and Part 2, I discuss two
additional design patterns (Null Object and MVC) in Part 3. They are
equally important, commonly used, and well-known patterns in
today’s world of programming.
Finally, in Part 4 of the book, I discuss the criticism of design patterns
and give you an overview of anti-patterns, which are also important
when you implement the concepts of design patterns in your
applications. I also include a FAQ on design patterns.
Starting from Chapter 2, each chapter is divided into six major parts:
a definition (which is termed as “intent” in the GoF book), a core
concept, a real-life example, a computer/coding world example, at
least one sample program with various outputs, and the “Q&A
Session” section. These “Q&A Session” sections can help you learn
about each pattern in more depth.
You can download the source code of the book from the publisher’s
website. I have a plan to maintain the errata and, if required, I can
also make updates/announcements there. So, I suggest that you visit
those pages to receive any important corrections or updates.

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.

Figure FM-1 Download link for Eclipse


Before I start coding, I use pen/pencils and paper. Sometimes, I use
markers and a whiteboard. But when I show my programs in a book,
I understand that I need to present these diagrams in a better shape.
So, I use some tools to draw the class diagrams from my code. In the
second edition of the book, I used ObjectAid Uml Explorer in the
Eclipse editor. It is a lightweight tool for Eclipse. But it did not work
for me with the updated versions of Eclipse. So, this time I used
another nice tool, Papyrus. It is an open-source UML 2 tool based on
Eclipse and licensed under the EPL. I was able to generate class
diagrams easily using this tool. In some cases, to make them better, I
added notes or edited a few things in the diagram so that you can
understand it easily. For example, consider Figure FM-2 (taken from
Chapter 14, when I discuss the Bridge pattern). You can understand
easily that the Papyrus tool will not show you the markers for
Hierarchy-1, Hierarchy-2, or BRIDGE inside the dashed rectangle. I
edited the original diagram to help you understand the components
better.

Figure FM-2 A class diagram that is taken from Chapter 14

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.

Guidelines for Using This Book


Here are some suggestions so you can use the book more effectively:
I assume that you have some idea about the GoF design patterns. If
you are absolutely new to design patterns, I suggest you quickly go
through Appendix A. This appendix will help you to become familiar
with the basic concepts of design patterns.
If you are confident with the coverage of Appendix A, you can start
with any part of the book. But I suggest you go through the chapters
sequentially. The reason is that some fundamental design techniques
may be discussed in the Q&A Sessions of a previous chapter, and I do
not repeat those techniques in later chapters.
I believe that the output of the programs in this book should not vary
in other environments, but you know the nature of software: it is
naughty. So, I recommend that if you want to see the exact same
output, it’s best if you can mimic the same environment.

Conventions Used in This Book


Here I mention only two points. In a very few places, to avoid more
typing, I have used the word “he” only. Please treat it as “he” or “she”,
whichever applies to you.
To execute a program, I put all parts in the same folder/package. So,
in most cases, I chose the package-private visibility. But if you want, you
can increase the respective visibilities to public to reuse those parts. I
used separate packages for separate programs to help you find all parts
of a program at the same place.
Finally, all the output and code of the book follow the same font and
structure. To draw your attention, in some places, I have made them
bold. For example, consider the following output fragment (taken from
Chapter 15, when I discuss the Template Method pattern) and the line
in bold:
***Template Method Pattern with a hook method.***
Computer Science course structure:
1. Mathematics

2. Soft skills

3. Object-Oriented Programming

4. Compiler construction.

Electronics course structure:


1. Mathematics

2. Soft skills

3. Digital Logic and Circuit Theory

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/.

Shekhar Kumar Maravi


is a Lead Engineer in Design and
Development whose main interests are
programming languages, algorithms, and
data structures. He obtained his Master’s
degree in Computer Science and
Engineering from Indian Institute of
Technology Bombay. After graduation, he
joined Hewlett-Packard’s R&D Hub in
India to work on printer firmware.
Currently he is a technical lead engineer
for automated pathology lab diagnostic
devices at Siemens Healthcare R&D
division. He can be reached by email at
[email protected] or via LinkedIn at
www.linkedin.com/in/shekharmaravi.
Part I
Foundation
Foundation
Part I consists of two chapters. In this part, you’ll see the usage of
SOLID principles. They are a combination of five design guidelines.
The Simple Factory pattern
In an object-oriented programming world, there is no shortage of
principles, but these are the fundamental design guidelines for making
a better application. This part shows you the case studies using (and
without using) these principles and helps you think about their
importance. A detailed study of them can help you make efficient and
flexible applications.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
V. Sarcar, Java Design Patterns
https://doi.org/10.1007/978-1-4842-7971-7_1

1. Understanding SOLID Principles


Vaskaran Sarcar1
(1) Garia, Kolkata, India

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.

Single Responsibility Principle


A class acts like a container that can hold many things such as data, properties, or methods. If you put in too
much data or methods that are not related to each other, you end up with a bulky class that can create
problems in the future. Let’s consider an example. Suppose you create a class with multiple methods that do
different things. In such a case, even if you make a small change in one method, you need to retest the whole
class again to ensure the workflow is correct. Thus, changes in one method can impact the other related
method(s) in the class. This is why the single responsibility principle opposes this idea of putting multiple
responsibilities in a class. It says that a class should have only one reason to change.
So, before you make a class, identify the responsibility or purpose of the class. If multiple members help
you achieve a single purpose, it is ok to place all the members inside the class.

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;
}

public void displayEmpDetail(){


System.out.println("The employee name: " +
lastName+","+firstName);
System.out.println("This employee has " +
experienceInYears +"
years of experience.");
}

public String checkSeniority(double experienceInYears){


return experienceInYears > 5 ?"senior":"junior";
}
public String generateEmpId(String empFirstName){
int random = new Random().nextInt(1000);
empId = empFirstName.substring(0,1)+random;
return empId;
}
}

// Client.java
class Client {
public static void main(String[] args) {
System.out.println("*** A demo without SRP.***");

Employee robin = new Employee("Robin", "Smith", 7.5);


showEmpDetail(robin);

System.out.println("\n*******\n");

Employee kevin = new Employee("Kevin", "Proctor", 3.2);


showEmpDetail(kevin);
}

private static void showEmpDetail(Employee emp) {


emp.displayEmpDetail();
System.out.println("The employee id: "+
emp.generateEmpId(emp.firstName));
System.out.println("This employee is a " +
emp.checkSeniority(emp.experienceInYears)+
" employee.");
}

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.

*** A demo without SRP.***


The employee name: Smith,Robin
Other documents randomly have
different content
crew to take to, one, the jolly-boat, was lost; the ship was now fast
falling over on her beam-ends, and directions were given to cut away
the masts; but the crash caused the ship to part in two, and a few
seconds afterwards she again broke right across, between the fore
and main-masts.
“A considerable crowd of men had got into the pinnace (or boat),
in hopes that she might float as the ship sunk; but the captain, seeing
that the boat was overloaded, desired some twenty men to quit her,
and his orders were as promptly obeyed as they were coolly given, so
completely was discipline maintained by the character of the
commander, and consequent confidence of the crew. The pinnace
then floated, but was immediately upset by a sea; the people in her,
however, imitating the conduct of their captain, retained their self-
possession, and, by great exertions, righted the boat, and got her
clear of the wreck, where, at a little distance off, they waited further
orders from their captain, who, with forty men, still clung to the
remains of the vessel. It was now, however, absolutely necessary to
quit it, as the wreck was disappearing rapidly; and in order to enable
the boats to contain them, the men, as removed to the pinnace, were
laid flat in the bottom like herrings in a cask, while the small boats
returned to pick up the rest, which was at last accomplished with
great difficulty; but, except the despatches, which had been secured
by the captain from the first, and a chronometer, everything on
board was lost. The pinnace now contained eighty persons, the cutter
forty-two, and the gig eighteen, with which load they barely floated,
the captain being the very last person to quit the wreck of the ship;
and hardly had he got into the boat when the last fragments
disappeared: three hearty cheers were given by the gallant crew. The
fog continued as dense as ever, and they had no means of knowing in
which direction to proceed, and if it had not been for a small
compass, which one man had appended to his watch, for a toy, it is
most probable that they would not yet have been preserved; at last
they were all landed in safety, about twenty miles from Halifax,
nearly naked, wet through and shivering, and miserably cramped by
the close crowding in the boats. The captain took the worst provided,
and most fatigued, round to the harbour in the boats, and the rest,
under the officers, marched across the country in three divisions,
with as much regularity as if going well-appointed on some regular
expedition, though very few had any shoes, and they had to traverse
a country only partially cleared; the same evening the whole crew,
without one missing, officers, men, and boys assembled at Halifax in
as exact order as if their ship had met with no accident.”
“That is a very striking account indeed! Captain Hickey was a
noble fellow!”
“The second story is tragically different from the first, and presents
one of the most striking pictures of passive courage ever presented to
the contemplation. A captain of a ship of war, whose sole object of
ambition was to distinguish himself by capturing an enemy’s vessel,
conceived that his surest mode of obtaining the fulfilment of his
wishes was by disciplining his crew so strictly, that, in the event of an
engagement, he would be sure of victory by his superiority in this
respect; but, in order to obtain this, he harassed his crew by such
strict regulations, such constant and unremitting exertions, and such
excessive severity, as to alienate all affection, and to bring his crew to
the verge of insubordination.
“The day at length arrived when his expectations seemed about to
be realized. A strange sail appeared in sight, which was soon made
out to be an enemy. He summoned his crew, and addressed them in
an energetic speech; reminding them of their duty, and of the glory
which awaited them; he gave orders to clear for action, and was
instantly and scrupulously obeyed. But the hour of retribution was at
hand. His crew knew of his ambition; knew it to be the source of
their suffering, and determined to be revenged in the fullest manner.
Their own spirit forbad them to do anything cowardly or mean, but
they stood to their guns, and, when the enemy began the
engagement, they kept their places, and refused to return a shot; in
vain their commander and his officers reproached, exhorted,
supplicated; with their arms folded they waited their fate, nor
flinched while broadside after broadside struck them down. The
battle, or rather the attack, was soon over; the enemy, surprised at
the non-resistance, boarded the English vessel, and found the
officers and their crew nearly all destroyed. The captain lived long
enough to feel the bitter anguish of disappointment, and to be
conscious of having been the cause; but he fell at last, before the
vessel was taken possession of.”
“That was carrying discipline too far, however. Poor fellows! How
those men must have hated the captain!”
“No doubt they did. Had not the captain been blinded by his own
selfishness, he would have seen their discontent. Whether in the
service or out of it, that man who disregards the feelings of others is
not fit to be placed in authority. When men are tried too much, the
heart is like a full cup, that a drop will make run over. I was once
present when a young officer was very hard on an old soldier, whom
he at last called a stupid old fool. The veteran at once lost all
command of himself—he stepped from the ranks and told the young
officer, that he had served his country for years, while he, his officer,
had never smelt gunpowder. The officer had been in the wrong, and
was prudently advised to pass by the outbreak of the old soldier.
Before now, I have seen men on the very eve of mutiny, when a
prudent and considerate word on the part of an officer, has broken
their proud hearts at once, and brought them to a sense of their duty.
Englishmen hate oppression, and it ought never to be practised.
When officers temper the discipline of the service with due
consideration, and kindly feeling, soldiers, sailors, and marines, are
ready to follow them through fire and water.”
CHAPTER V.

Alexander the Great.—Frederick the Great.—Charles XII.—Peter the Great.—


Buonaparte.—Duke of Marlborough.—Hastings.—Bannockburn.—Cressy.—
Poictiers.—Agincourt.—Bosworth Field.—Blenheim.—Culloden.—Prague.—
Quebec.—Battles of Marathon, Thermopylæ, and the siege of Troy.—
Preparation for a battle.—The battle array.—General De Zeithen.—Monument
of Peter the Great.—Duke of Marlborough.

“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.

‘He that outlives this hour, and comes safe home,


Shall stand on tiptoe when this day is named,
And rouse him at the name of Crispian:
He that outlives this day, and sees old age,
Will yearly on the Vigil feast his neighbours,
And say, To-morrow is St. Crispin’s-day.’”

“Ay! those lines are in Enfield’s Speaker—almost every boy knows


them.”
“The battle of Bosworth Field is much celebrated. King Richard III.
there lost his crown and his life. The battle of Blenheim was fought
by the great Marlborough and Prince Eugene, against the French and
Bavarians. Twelve thousand of the enemy were slain or drowned in
the river.
‘Deep groaned the water with the dying sound!
Repeated wounds the redd’ning river dyed,
And the warm purple circled on the tyde.’

“At Culloden in Scotland the Duke of Cumberland gained a


complete victory over the Scots. It is said, that the duke’s soldiers
practised great cruelty towards the defenceless inhabitants after the
battle. If so, it was a disgrace to them. ‘Ready and steady,’ is a good
maxim for soldiers and sailors, ready for duty and steady in danger,
but cold-hearted cruelty is a black blot on a soldier’s brow. The evils
of war are bad enough in themselves. He is no true-hearted soldier
who can injure the defenceless, whatever be the nation to which he
belongs. Mercy is a Godlike attribute; practice it, boys, whenever it is
in your power.”
“Those cruel soldiers were not worthy the name of Englishmen.”
“At the battle of Prague the King of Prussia defeated the Austrians,
but the brave Marshal Schwerin, a Prussian general, there lost his
life. At Minden Prince Ferdinand beat the French, with great
slaughter.”
“Where is Minden?”
“In Germany. At Quebec the celebrated Wolfe was killed, dying in
the moment of victory. ‘They run! they run!’ said an officer who
supported the dying warrior. ‘Who run?’ inquired Wolfe eagerly. ‘The
French!’ replied the lieutenant. ‘Then,’ said Wolfe, ‘I die happy!’”
“How sad to die just as he had got the victory!”
“The storming of Seringapatam, and the battle of Marengo, were
two famous engagements; and the battles in Spain were very
numerous. Among them were those of Corunna, Ciudad Rodrigo,
Badajos, Salamanca, Vittoria, and St. Sebastian. After all these came
the battle of battles, Waterloo, won by the conqueror of conquerors,
Wellington.”
“What a number of battles you have mentioned!”
“Remember, boys, I am an old soldier, and am therefore at home
in speaking of them. From time immemorial there have been battles,
and, so long as men are what they are, there will be; but for all that it
becomes us to encourage a spirit of peace and good-will to all men. It
is only when the oppressed are to be protected, when injuries are to
be redressed and rights defended, that the sword ought ever to be
drawn from its scabbard, nor even then if those ends can be obtained
by more peaceable means. In an unworthy cause battle becomes
murder, and victory a polluted and unholy thing.
“As the battle of Marathon is so often alluded to in the pages of
history, I will just tell you, in a few words, the particulars of the fight.
Marathon was a village of Attica, about ten miles from Athens, in
Greece; and Miltiades, an Athenian general, with ten thousand men,
though some say twenty-thousand, defeated, in the adjacent plain,
the Persian army, under Datis, of one hundred thousand infantry,
and ten thousand horse. By this victory the terror of the Persian
power was dispelled, and the enthusiastic valour of the Greeks called
forth.”
“How long is it since the battle of Marathon?”
“More than two thousand years. The Grecian orators, whenever
they wanted to excite their countrymen to warlike deeds, always
reminded them of what ten thousand Athenians achieved on the
plains of Marathon. The famous siege of Troy took place almost a
thousand years before then.”
“Why, then it is three thousand years since the siege of Troy?”
“It is, boys. You know, I dare say, that Homer composed two
poems, the Iliad and the Odyssey, on the subject; but poets are not
often the most correct historians. After a siege of ten years, the
Greeks took Troy from the Trojans, it is supposed by stratagem, and
then burnt it to the ground.”
“Ay! Did they not send a wooden horse into the place?”
“So the tale goes. It is said, that the Greeks caused a large wooden
horse to be made, and hid in it a number of their bravest warriors.
They then pretended to give up the siege. At night, after the wooden
horse had been taken into the city, the inclosed warriors rushed out,
and opened the gates to their companions.”
“But do you not think the tale is true?”
“Indeed I do not. Now we are speaking of ancient battles, I will
mention that of Thermopylæ. Thermopylæ was a narrow defile,
leading from Thessaly into some Grecian districts; it was, indeed,
looked on as the gate of Greece. Here Leonidas, the Spartan general,
with a small band of devoted warriors, repulsed the army of Xerxes,
King of Persia, consisting, say some, of three million men. Xerxes
was amazed and confounded; but, having been informed of another
pass over the mountains, he availed himself of it. Leonidas being
attacked in the rear by twenty-four thousand men, and in front by
the main body of Persians, could no longer resist his overwhelming
adversary, but he and every man with him, scorning to surrender,
fought till they died.”
“Battles must be very different now, to what they used to be.”
“They are indeed. Gunpowder has altogether changed military
tactics. Strength and courage formerly obtained victories, but now, a
knowledge of tactics will often enable a small body of men to
overcome a larger one. A battle should never be fought when it can
be avoided. It is said to be the last resource of a good general. If skill
and stratagem can attain an object, fighting is altogether out of the
question. When, however, a battle becomes inevitable, the first thing
is to take advantage of the ground, for oftentimes the possession of a
hill, a thicket, a village, or of a single building, is of great
consequence. If you had been at Waterloo, and seen what efforts
were made to possess the house called Hougomont, I should have no
occasion to say a word on this point.”
“But why is a hill, or a thicket, or a house, of so much
consequence?”
“Because these things not only protect troops, but enable them to
annoy their enemies by preventing them from forming, and picking
off their officers. It is a great advantage, also, in a battle, to have the
wind and sun in your favour; to meet an enemy with the wind and
dust against you, and the sun in your eyes, is very trying. The
artillery should be distributed with great care, for it forms, in most
cases, the principal strength of an army; and the horse and foot
should be posted on ground the fittest for their operations.”
“But, how can an army fire cannon without killing their own
soldiers, for they must at times be mingled together with the
enemy?”
“In such a case the artillery moves its position, and only plays
when it can do so on the enemy alone. The battle array generally
consists of three lines, the front, the rear, and the reserve. An
attacking army is generally divided into three parts, the main body,
and the two wings. And the battle array is formed by dividing each of
these into three lines, the front, the rear, and the reserve; the artillery
is divided along the front of the first line, and the treasure, provision,
and baggage, are removed to a safe place before the engagement.”
“Ay! It must be very necessary to take care of them.”
“Prussia has long been a warlike country; for Frederick the Great
called forth the military energies of his people. In Prussia, every able-
bodied man of the kingdom is required to perform a limited service
in the army. At twenty, he enters the regular army for three years,
unless favoured by some regulation, which limits the term to one
year. From twenty-three to twenty-five he belongs to the war reserve,
when he enters the first ban of the landwehr, and continues to his
thirty-second year, after which he serves another seven years in the
second ban of the landwehr. After the fortieth year, he ranks till the
fiftieth in the landsturm, or levée en masse of the whole population.”
“If every one in Prussia is compelled to be a soldier, why, then, Old
England for ever!”
“Frederick the Great was distinguished for great talents as a
warrior, a statesman, and a man of science and literature. His
enemies were numerous, his exploits brilliant, and his tactics and
policy eminently successful. Surrounded on all sides by his foes, he
hurried from one part of his dominions to another with equal
celerity, courage, prudence, and perseverance, and though sorely
tried, overcame all his difficulties, and gained the name of Frederick
the Great.”
“Why, he was another Buonaparte!”
“Before the battle of Rosbach, which led to the most celebrated of
all the King of Prussia’s victories, Frederick addressed his little army,
not amounting to more than twenty-five thousand men, in nearly the
following words:—‘My brave soldiers, the hour is come in which all
that is, and all that ought to be dear to us, depends upon the swords
that are now drawn for the battle. Time permits me to say but little,
nor is there occasion to say much. You know that there is no labour,
no hunger, no cold, no watching, no danger, that I have not shared
with you hitherto; and you now see me ready to lay down my life with
you, and for you. All I ask, is the same pledge of fidelity and affection
that I give. Acquit yourselves like men, and put your confidence in
God.’
“The effect of this speech was indescribable. The soldiers answered
it by an universal shout, and their looks and demeanour became
animated to a sort of heroic frenzy.
“Frederick led on his troops in person, exposed to the hottest of
the fire. The enemy, for a few moments, made a gallant resistance,
but overwhelmed by the headlong intrepidity of the Prussians, they,
at length, gave way in every part, and fled in the utmost disorder.
Night alone saved from total destruction the scattered remains of an
army which, in the morning, was double the number of the
conquerors.”
“A speech from a general to his army seems to do a great deal
towards getting a victory.”
“Frederick was an excellent general, and the soul of perseverance.
So severe was the duty in some of his regiments of cavalry, that war
was said to be a mitigation rather than an addition to their
hardships. Frederick had a very skilful general, of the name of De
Zeithen, whom he had somewhat neglected in a time of peace. When
war broke out, he was anxious to avail himself of his military talents
and unequalled courage; but De Zeithen had too keen a
remembrance of the past neglect to proffer his services. After trying
all other methods in vain, to persuade him to his wishes, Frederick at
last said, he knew that his old and faithful general, De Zeithen, would
never see his King in difficulty, and deny him his assistance. De
Zeithen’s proud heart was melted by this appeal of his sovereign,
and, falling on his knees, with tears rolling down his cheeks, he
devoted his sword while he had life to the service of his King.”
“Old General Zeithen was won over then. Frederick knew the way
to the old man’s heart.”
“When Frederick took the field against his enemies, in his last war,
he was in his sixty-seventh year. ‘We have all grown old,’ said he to
his assembled officers, ‘in the career of arms, and have shared
together the glories and the fatigues of our former wars. You are,
doubtless, as unwilling as myself to shed blood, but new dangers,
with which the empire and my territories are alike menaced, oblige
me to take the most efficacious measures to dissipate the threatening
storm. I cannot, therefore, avoid calling you once more to defend
your country. It will give me the most lively satisfaction when I shall
have to recompense you for your fresh services. I shall not appear
during the campaign with a luxurious camp equipage; you know I
have never cared for such a thing; my actual infirmities will,
however, prevent my making the campaign as I should have done
during the vigour of my life. I shall, in marches, make use of a
carriage, but on a day of battle you may be sure of seeing me on
horseback among you as formerly.’”
“The old King was ready to the last to play the general.”
“Charles XII. of Sweden delighted in war, and never did warrior
surpass him in daring; but he was reckless almost to insanity. At the
battle of Narva, with only twenty thousand men, he defeated the
Czar, Peter the Great, who had, it is said, one hundred thousand; but
at the battle of Pultowa in Russia, Peter the Great overcame him,
when he fled for safety to the dominions of the Turk. He died in the
trenches of Frederickshall in Norway, some say by a cannon shot, but
others say by the pistol of one of his own soldiers.
‘His fall was destined to a distant strand,
A petty fortress, and a dubious hand:
He left the name at which the world grew pale
To point a moral, or adorn a tale.’”

“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.

Uniforms.—Old Admirals in the Naval Gallery at Greenwich.—Admiral Forbes


and the Duke of Bedford.—Dress of an admiral of the fleet.—Captains and
commanders.—Full dress of the officers of the life-guards.—Dragoon-guards.
—Light dragoons.—Lancers.—Hussars.—King George the Fourth and the life-
guardsman.—Full dress of the officers of the foot-guards.—Infantry of the line.
—Light infantry.—Fusiliers.—Highlanders.—Riflemen.—Sir Samuel Hood and
the new-made boatswain.

“I have said nothing of the uniforms worn by soldiers and sailors,


and will now enter a little on the subject. If you were to see the
paintings of the hearty old admirals in the Naval Gallery of
Greenwich Hospital, they would surprise you. Some of these tough
old tars look as though they would not alter a brass button of their
coats, if it affected the honour of old England, to prevent the
broadside of an enemy from sending them to the bottom of the
ocean. Their dresses are so odd and so different one from another
that you would hardly think they were all admirals. Some have long
curled wigs on; some have red coats, some blue, and some brown;
some are clad in armour; some in buff leathern jerkins; some in loose
robes, and others in red velvet gowns with ermine capes. In old times
there was no fixed uniform for the navy; and, besides, some of these
admirals are painted as they appeared on state occasions. In the
reign of George II. some of these old heroes, talking over the subject
of dress at one of their clubs, came to a resolution ‘That a uniform
dress is useful and necessary for commissioned officers, agreeably to
the practice of other nations.’ No sooner was this resolution passed,
than a committee appointed Admiral Forbes to wait on the Duke of
Bedford, who was then the First Lord of the Admiralty.”
“And did he go to the duke?”
“He did. He was shown into a room surrounded with dresses, and
the duke asked him which of them he thought the most suitable?
‘Oh!’ said he, ‘the dress should be either red and blue, or blue and
red, for these are the national colours.’ ‘That may be,’ replied his
Grace, ‘but the King has settled the matter differently. He saw my
duchess riding in the park the other day, in a habit of blue faced with
white; it took his fancy, and he has ordered that it shall become the
uniform of the royal navy.’ This uniform of blue and white was
established in the year 1748, and remained unaltered, as to colour,
until a few years ago, when King William IV. changed the white
facing to a red one. At the present time we have our national colours
blue and red.”
“But is there no lace about an admiral’s uniform?”
“Oh, yes. In 1812 the full dress of the admiral of the fleet was a coat
of blue cloth, with white cloth lapelles laced, and cuffs, with five laces
round the cuffs. The admirals the same, with only four laces on the
cuffs. The vice-admirals, with only three laces on the cuffs. The rear-
admiral, with two laces on the cuffs. The captain to the admiral of the
fleet wore the undress or frock-uniform of rear-admirals. Captains
and commanders wore uniforms of the same pattern. Lieutenants
wore a uniform of the same pattern as captains, but without lace, and
masters’-mates and midshipmen dressed as they did before. The
officers wore epaulettes, according to their ranks.”
“Epaulettes! What, do officers in the navy wear epaulettes?”
“Yes! Epaulettes in the navy are of gold lace; and officers in the
army or navy who disgrace their arms are liable to have their
epaulettes torn from their shoulders. According to an order of the
Admiralty, in 1812, captains above three years post have two
epaulettes, with a silver crown over a silver anchor; and post-
captains under three years, have two, with a silver anchor without
the crown. Commanders have two plain epaulettes; lieutenants, one;
rear-admirals, two, with a star on the strap of each; vice-admirals,
two stars, and admirals three stars. Marines used to wear two silver
epaulettes, but, for good conduct, they are now called royal, and
allowed to wear gold epaulettes, according to the rank they have
acquired.”
“Now, please to give us the uniform of soldiers; for that is very
striking.”
“If I were jesting, boys, I should say, the most striking part of a
soldier is his sword, but in gravely describing things as they are, I
must say that his dress is the most conspicuous thing about him.
Were soldiers clad in common clothes their bravery would suffer as
much as their appearance in our estimation.”
“Oh! it would never do for soldiers to dress in common clothes; we
should not know that they were soldiers.”
“Red and blue are the prevailing colours in the army. You will,
perhaps, like to know something about the full dress of the officers;
the dress of the men is, of course, of an inferior quality.”
“Yes. The dress of the officers, if you please. Some officers that we
have seen have cut a very grand appearance.”
“Passing by, for the present, the dress of general officers, staff
officers, the personal staff attached to general officers, the staff of
garrisons, the Royal Military College, the Royal Military Asylum, the
Cavalry Depôt, garrison of Chatham, and the civil departments, I will
come at once to the dress of officers of regiments of cavalry. These
are, as I have told you, the life-guards, the royal regiment of horse-
guards, the dragoon-guards, and heavy dragoons, the light dragoons,
the lancers and the hussars. As changes are often introduced in the
dress of officers, it is possible that my account may not in every
particular be correct, but I will be as exact as I can.”
“Now, then, for the dress of the life-guards.”
“The officers of the life-guards, when in full dress, wear a scarlet
coat, single-breasted, which has a blue velvet Prussian collar,
embroidered, and a bear-skin cap, fourteen inches deep in front,
with white swan feathers. So you see that British officers may show
the white feather without being suspected of cowardice. Their
pantaloons are of white leather; their swords have half-basket steel-
pierced hilts, with steel scabbards, and crimson and gold sword-
knots, and their gloves are white leather gauntlets. When in their
undress, they wear blue pantaloons, and a blue cloth forage-cap. The
shabraque, or horse-cloth, of the life-guards is blue, trimmed with
lace and embroidered. An officer’s uniform is often of great value;
but though to lose his full-dress would be a misfortune, to be stript
of his honour would be a greater loss. Directly after the battle of
Waterloo his royal highness the Prince of Wales, the Prince Regent,
afterward George IV. declared himself colonel-in-chief of the
household cavalry brigade. This was done as a mark of attention to
the first and second regiments of life-guards, and the royal horse-
guards (blue), who had conducted themselves very bravely in the
battle. When the Prince Regent became King he still held the
appointment, and William IV. afterwards followed his example.
“The life-guards must appear grand enough mounted on their fine
horses. Now for the horse-guards, for they come next.”
“The life-guards do, as you say, appear grand, but there is many a
foot-soldier with his coarse, grey great-coat, and knapsack on his
back, ay, and many a common sailor, in his plain blue jacket, that
carries as brave a heart in his bosom as a life-guardsman. In the
royal regiment of horse-guards the officers wear a blue coat with
embroidered scarlet collar. Many parts of their dress resemble that of
the life-guards, but their feathers are red, and their waist-belt white
silk; their horse-furniture is scarlet with gold-lace and embroidery.”
“How handsome their horses must look in embroidery, scarlet, and
gold lace!”
“The officers of the dragoon-guards and heavy dragoons wear a
scarlet coat with collar, cuffs, and turn-backs of regimental facings,
and embroidered skirt-ornaments, and helmets of gilt-metal, with
bear-skin crest. Their trousers are blue, and gold lace. Their horse-
furniture is a high-mounting saddle, black sheep-skin shabraque
edged with scarlet cloth, with dress housing of blue cloth and gold
lace, a bear-skin flounce, and white web collar.”
“Gilt helmets! How they must glitter in the sun!”
“They do. A double-breasted scarlet jacket, with gold basket braid,
is worn by the officers of the light dragoons, if it be not already
changed for a blue one. Their chaco, or cap, is black beaver, with
white drooping cock-tail feathers, trousers dark blue and gold lace,
girdle and waist-belt gold lace. Their horse-furniture is embroidered
blue cloth.”
“Why are dragoons called light and heavy?”
“The heavy dragoons are larger men, and have heavier and
stronger horses. Light troops are the most nimble, and heavy the
most powerful. The lancers, like the light dragoons, wear a double-
breasted scarlet jacket; the cuff and collar are blue, and the button-
holes embroidered; the cap-plume is a black cockade, their waist-belt
and pouch-belt are of gold lace, and the pouch-box scarlet leather;
their shabraque is of blue cloth embroidered.”
“The lancers wear scarlet jackets, but the life-guards wear scarlet
coats; we remember that.”
“The clothing of Prince Albert’s hussars, I believe, is, blue dress
jacket, pelisse all blue, with fur cuffs and collars; trousers, crimson
with yellow stripes; undress jackets, blue; the hurby, or fur-cap, of
seal-skin; the horse covered with a crimson shabraque, ornamented
with German silver. On arrival of Prince Albert in England a
squadron of the hussars escorted him from Canterbury to
Sittingbourne. The band played on that occasion in front of the
fountain at Canterbury, when his royal highness presented them with
ten pounds. From the circumstance of this being the first regiment
which received him on the English shores, and of his royal highness
being struck with their fine appearance, Prince Albert, it is thought,
selected it as his own.”
“Would it not be better if soldiers were clad in armour, as the
knights used to be in old times. Nothing then could hurt them, unless
it was a cannon ball?”
“It has been discovered that inside armour is better than outside.
The courage of the heart is a stronger defence than the breastplate,
and the skill and strength of the arm affords more security than a
helmet of iron. Philip de Comines tells us of a number of armed
Italian knights, who at the battle of Fournoue, being overthrown,
were unable to rise on account of the weight of their armour; they
were therefore taken prisoners, but they could not be killed until they
were broken up like huge lobsters, with wood-cutters’ axes, by the
servants and followers of the army.”
“Dreadful! dreadful!”
“James I. when speaking of armour, said, ‘that it not only
protected the wearer from injury but also prevented him from doing
injury to others.’ The following anecdote is told of George IV. After
the battle of Waterloo, it was proposed to make some change in the
dress of the life-guards. The King ordered one of the soldiers to be
sent for, who was said to have slain in single combat six or seven
French cuirassiers. He was asked a variety of questions, that his
opinion might be obtained as to what kind of defence or dress was
best for a soldier; but the King saw, by his answers, that he was
overawed, and biassed in his opinion by the presence of the King,
and also of his own officers, for he assented to everything. At last the
King said to him, ‘Well, if you were going to have such another day’s
work as you had at Waterloo, how would you like to be dressed?’
‘Why, please your Majesty, in that case, I had rather be in my shirt-
sleeves.’”
“It seems, that armour would never do for soldiers. What is the full
uniform of the infantry officers?”
“I have told you so much of the dress of the cavalry that I can only
say very little of the infantry. The officers of the foot-guards wear a
scarlet coat, with blue Prussian collar embroidered with gold, blue
trousers, gold epaulettes, and bear-skin cap. The infantry of the line
wear scarlet coatees, trousers of Oxford-mixture cloth, or white
linen, with black beaver caps and white feather; and the light-
infantry are dressed much the same, but their forage-cap is of dark
green cloth, with an embroidered bugle in front.”
“Ay! the bugle in front of the cap is just right for the light infantry.”
“The light infantry are an active set of fellows, here, there, and
everywhere at the shortest intervals of time. The fusiliers’ dress
differs little from that of the infantry of the line, but their cap is bear-
skin, with a white hackle feather. The Highland regiments wear a
scarlet jacket, belted plaid, kilt, shoes and buckles, with a cocked
bonnet, carrying six black ostrich feathers.”
“The dress of the Highlander is the oddest of all!”
“The Highlanders are famous with the broadsword. Perhaps you
may remember Sir Walter Scott’s description of the fight between
Fitz James and Roderick Dhu.”
“Ill fared it then with Roderick Dhu,
That on the field his targe he threw,
Whose brazen studs and tough bull-hide
Had death so often dashed aside;
For trained abroad his arms to wield,
Fitz James’s blade was sword and shield;
He practised every pass and ward,
To thrust, to strike, to feint, to guard;
While, less expert, though stronger far,
The Gael maintained unequal war.
Three times in closing strife they stood,
And thrice the Saxon sword drank blood;
No stinted draught, no scanty tide,
The gushing flood the tartans dyed.
Fierce Roderick felt the fatal drain,
And showered his blows like wintry rain;
And as firm rock, or castle roof,
Against the winter shower is proof,
The foe, invulnerable, still
Foiled his wild rage by steady skill;
Till at advantage ta’en, his brand
Forced Roderick’s weapon from his hand,
And, backwards borne upon the lea,
Brought the proud chieftain to his knee.”

“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.

Weapons of war.—Artillery.—Train of artillery.—Chevaux-de-frise.—Bows and


arrows.—The old archer.—The musket.—The bayonet.—Captain Von Selmnitz.
—Broad-swords.—Highlanders.—Artillery and stores sent to Spain.—James II.
of Scotland.—Buonaparte and Colonel Evain.—Wooden cannon.—Brass
twenty-four-pounder from the wreck of the Royal George.—The brass sixty-
eight-pounder in the Tower, called the ‘Great Harry,’ a beautiful mortar.—The
new destructive power.

“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

You might also like