We all have unique thought processes. So, in the early days of software development, engineers faced a common problem—there was no standard to instruct them how to design their applications. Each team followed their own style, and when a new member (experienced or unexperienced) joined an existing team, understanding the architecture was a gigantic task. Senior or experienced members of the team would need to explain the advantages of the existing architecture and why alternative designs were not considered. The experienced developer also would know how to reduce future efforts by simply reusing the concepts already in place. Design patterns address this kind of issue and provide a common platform for all developers. You can think of them as the recorded experience of experts in the field. Patterns were intended to be applied in object-oriented designs with the intention of reuse.
In 1994, Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides published the book Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1994). In this book, they introduced the concept of design patterns in software development. These authors became known as the Gang of Four. We will refer them as the GoF throughout this book. The GoF described 23 patterns that were developed by the common experiences of software developers over a period of time. Nowadays, when a new member joins a development team, the developer first learns about the design patterns of the existing system. Then the developer learns about the existing architecture. This allows the developer to actively participate in the development process within a short period of time.
The first concept of a real-life design pattern came from the building architect Christopher Alexander. During his lifetime, he discovered that many of the problems he faced were similar in nature. So, he tried to address those issues with similar types of solutions.
Each pattern describes a problem, which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice.
—Christopher Alexander
The GoF assured us that though these patterns were described for buildings and towns, the same concepts can be applied to patterns in object-oriented design. We can substitute the original concepts of walls and doors with objects and interfaces. The common thing in both fields is that, at their cores, patterns are solutions to common problems.
The GoF discussed the original concepts in the context of C++. C# 1.0 was released in 2002, and at the time of this writing, C# 7.0 is available with Visual Studio 2017. In this book, I’ll examine the GoF’s original design patterns but with C#. The book is written in C#, but if you are familiar with any other popular programming languages such as Java, C++, and so on, you will be able to relate because I focus on the design patterns and not on the latest features of C#. In fact, I have purposely chosen simple examples to help you to understand these concepts easily.
The following are key points about design patterns:
A design pattern is a general, reusable solution for commonly occurring problems. The basic idea is that you can solve similar kinds of problems with similar kinds of solutions. In addition, these solutions have been tested over a long period of time.
Patterns generally provide a template of how to solve a problem and can be used in many different situations. At the same time, they help you to achieve the best possible design much faster.
Patterns are descriptions of how to create objects and classes and then customize them to solve a general design problem in a particular context.
The GoF discussed 23 design patterns. Each of these patterns focuses on a particular object-oriented design. Each pattern can also describe the consequences and trade-offs of use. The GoF categorized these 23 patterns based on their purposes, as shown here:
Creational patterns
These patterns abstract the instantiation process. You make the systems independent from how their objects are composed, created, and represented. The following five patterns are this category:
Singleton pattern
Prototype pattern
Factory Method pattern
Builder pattern
Abstract Factory pattern
Structural patterns
This category focuses on how classes and objects can be composed to form relatively large structures. They generally use inheritance to compose interfaces or implementations. The following seven patterns fall into this category:
Proxy pattern
Flyweight pattern
Composite pattern
Bridge pattern
Facade pattern
Decorator pattern
Adapter pattern
Behavioral patterns
Here the concentration is on algorithms and the assignment of responsibilities among objects. You also need to focus on the communication between them and how the objects are interconnected. The following 11 patterns fall into this category:
Observer pattern
Strategy pattern
Template Method pattern
Command pattern
Iterator pattern
Memento pattern
State pattern
Mediator pattern
Chain of Responsibility pattern
Visitor pattern
Interpreter pattern
The GoF made another classification based on scope, namely, whether the pattern primary focuses on the classes or its objects. Class patterns deal with classes and subclasses. They use inheritance mechanisms, which are static and fixed at compile time. Object patterns deal with objects that can change at run time. So, object patterns are dynamic.
For a quick reference, you can refer to the following table that was introduced by the GoF:
In this book, you can start with any pattern you like. I have chosen simple examples so that you can pick up the basic ideas quickly. Read about each pattern, practice, try to solve other problems with the these patterns, and then just keep coding. This process will help you to master the subject quickly.
What are differences between class patterns and object patterns?
In general, class patterns focus on static relationship, and object patterns can focus on dynamic relationships. As the names suggest, class patterns focus on classes and their subclasses, and object patterns focus on the object relationships.
The GoF further differentiated them as follows:
Class Patterns | Object Patterns | |
---|---|---|
Creational | Can defer object creation to subclasses | Can defer object creation to another object |
Structural | Focuses on the composition of classes (primarily uses the concept of inheritance) | Focuses on the different ways of composition of objects |
Behavioral | Describes the algorithms and execution flows | Describes how different objects can work together and complete a task |
Can two or more patterns be combined in an application?
Yes. In real-world scenarios, this type of activity is common.
Do these patterns depend on a particular programming language?
Programming languages can play an important role in pattern use. But the basic ideas are the same; patterns are just like templates, and they will give you some idea in advance of how you can solve a particular problem. In this book, I primarily focus on object-oriented programming with the concept of reuse. But instead of an object-oriented programming language, suppose you have chosen some other language like C. In that case, you may need to think about the core object-oriented principles such as inheritance, polymorphism, encapsulation, abstraction, and so on, and how to implement them. So, the choice of a particular language is always important because it may have some specialized features that can make your life easier.
Should we consider common data structures such as arrays and linked lists as design patterns?
The GoF clearly excludes these concepts, saying that they are not complex, domain-specific designs for an entire application or subsystem. They can be encoded in classes and reused as is. So, they are not your concern in this book.
This appendix lists some useful resources. The following are helpful books:
Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma et al. (Addison-Wesley, 1995)
Head First Design Patterns by Eric Freeman and Elisabeth Robson (O’Reilly, 2004)
Java Design Patterns by Vaskaran Sarcar (Apress, 2015)
Design Patterns For Dummies by Steve Holzner (Wiley Publishing, Inc, 2006)
Design Patterns in C# by Jean Paul (Kindle edition, 2012)
The following are helpful online resources/websites:
Congratulations! You have reached the end of our journey together. I believe you have enjoyed your learning experience, and this experience can help you to learn and experiment further in this category. I said earlier that if you repeatedly think about the discussions, examples, implementations, and questions and answers discussed in the book, you will have more clarity about them, you will feel more confident about them, and you will remake yourself in the programming world.
A detailed discussion of any particular design pattern would need many more pages, and the size of the book would be too gigantic to digest. So, what is next? You should not forget the basic principle that learning is a continuous process. This book was an attempt to encourage you to learn the core concepts in depth so that you can continue learning.
Still, learning by yourself will not be enough. I suggest you participate in open forums and discussions to get more clarity on the subjects in this book. This process will not only help you, it will help others also.
Lastly, I have a request: criticism is allowed, but please also let me know what you liked about this book. In general, an artistic view and open mind are required to discover the true efforts that are associated with any kind of work. Thank you and happy coding!
Abstract Factory pattern
Class Diagram
concept
GoF definition
illustration
implementation
Output
PetAnimalFactory
real-life example
Solution Explorer View
structure
WildAnimalFactory
Adapter pattern
class
Class Diagram
concept
Directed Graph Document
drawbacks
electrical outlet
GetArea() method
GoF definition
implementation
modified illustration
characteristics
implementation
Output
Solution Explorer View
object
Output
Solution Explorer View
user interface and database
Anti-patterns
catalog
causes
concepts
definition
refactoring
software developers
symptoms
Bridge pattern
advantages
challenges
Class Diagram
concept
electronic items
GoF definition
GUI frameworks
implementation
Output
simple subclassing
Solution Explorer View
State pattern
Builder pattern
Class Diagram
concept
ConcreteBuilder objects
converting RTF to ASCII
GoF definition
IBuilder interface
implementation
Output
real-life example
Solution Explorer View
vs. Strategy pattern
Chain of Responsibility pattern
advantages
AuthenticationErrorHandler
challenges
Class Diagram
concept
customer care representatives
vs. Decorator pattern
Directed Graph Document
EmailErrorHandler and FaxErrorHandler
GoF definition
implementation
message priorities
vs. Observer pattern
Output
request-handling mechanism
software application
Solution Explorer View
Class adapters
Command pattern
advantages
challenges
Class Diagram
concept
Directed Graph Document
GoF definition
implementation
vs. Interpreter pattern
invocation process
invoker
vs. Memento pattern
modified Class Diagram
modified implementation
Modified Output
Output
painting
receivers
Solution Explorer View
WPF
Common Language Runtime (CLR)
Composite pattern
abstract class
advantages
challenges
Class Diagram
college organization
concept
data structure
GoF definition
implementation
iterator design pattern
object-oriented programming
organization and employees
Output
Solution Explorer View
tree data structure
Criticisms
Decorator pattern
abstract method
advantages
Class Diagram
component
concept
disadvantages
dynamic behavior
dynamic binding
functionality
GoF definition
GUI-based toolkit
implementation
inheritance mechanism
original house
Output
polymorphism
single responsibility
Solution Explorer View
Facade pattern
vs. Adapter pattern
advantages
birthday party
vs. Builder pattern
challenges
Class Diagram
concept
ConstructMilanoRobot and DestroyMilanoRobot
Directed Graph Document
GoF definition
implementation
loose coupling
Output
Solution Explorer View
subsystems
Factory Method pattern
analysis
Class Diagram
concept
database users
Directed Graph Document
GoF definition
IAnimalFactory class
implementation
Output
Solution Explorer View
Flyweight pattern
advantages
business cards
challenges
Class Diagram
computer game
concept
GoF definition
implementation
improvements
modified Class Diagram
modified implementation
Modified Output
multithreading
nonshareable
Output
vs. Singleton pattern
small and large robots
Solution Explorer View
vs. State pattern
Garbage collection (GC)
allocated objects
automatic memory management
characteristics
coding
comment lines
compile
destructor method
developer command prompt
invoking Dispose()
prediction, output
Common Language Runtime (CLR)
compaction
destructors
dirty objects
Dispose() method
Finalize() method
finalizers, drawbacks
GC.Collect()
GC.SuppressFinalize(this)
IDisposable interface
implementation
longer-lived objects
low-priority thread
managed heap
memory consumption rate
Output
short-lived objects
System.GC.Collect() method
Interpreter pattern
advantages
challenges
Class Diagram
concept
GoF definition
grammar rules
implementation
Java compiler
Output
Solution Explorer View
translator, foreign language
Iterator pattern
challenges
Class Diagram
collection objects
concept
data structure, student records
Directed Graph Document
First(), Next(), IsDone(), and CurrentItem() methods
GoF definition
implementation
Output
Solution Explorer View
Mediator pattern
advantages
airplanes
analysis
Class Diagram
concept
disadvantages
vs. Facade pattern
GoF definition
implementation
interconnections, objects
modified implementation
Modified Output
vs. Observer pattern
Output
participants
registered participants
Solution Explorer View
Memento pattern
advantages
ArrayList
challenges
Class Diagram
concept
Directed Graph Document
drawing application
GoF definition
implementation
mathematical model
memento, originator, and caretaker
modified implementation
Modified Output
operations
Output
Solution Explorer View
Memory leaks
causes
CLR profiler
demonstration code
Diagnostic Tools
heap view, snapshots
leaking rate
IL code of Main() method
modified code
modified results
objects
online application
symptoms
System.OutOfMemoryException
tools
try/finally blocks
using statement
Model-view-controller (MVC) pattern
advantages
architecture, variations
challenges
Class Diagram
components
definition
implementation
Output
restaurant
Solution Explorer View
web programming frameworks
Windows Forms application
Null Object pattern
analysis, unwanted input
challenges
Class Diagram
concept
definition
faulty program
if/else blocks
immediate remedy
implementation
Output
Output with valid inputs
runtime exception
Solution Explorer View
vehicles
washing machine
Object adapters
Observer pattern
benefits
Chain of Responsibility
challenges
Class Diagram
concept
GoF definition
implementation
notifications
notifications from subject
one-to-many relationships
Output
Publisher-Subscriber model
Solution Explorer View
UI-based example
Prototype pattern
BasicCar object
Class Diagram
computer world example
concept
demonstration code
Directed Graph Document
GoF definition
implementation
Output
real-life example
Solution Explorer View
Proxy pattern
and adapters
Class Diagram
computer world example
concept
and decorators
Directed Graph Document
GoF definition
implementation
modified implementation
Modified Output
Output
real-life example
Solution Explorer View
Simple Factory pattern
challenges
characteristics
Class Diagram
concept
definition
Directed Graph Document
exception
Factory Method and Abstract Factory patterns
implementation
ISimpleFactory
Output
Solution Explorer View
static class
Wikipedia
Singleton pattern
challenges
characteristics
Class Diagram
computer world example
concept
vs. Factory Method pattern
GoF definition
implementation
Output
real-life example
Solution Explorer View
static initialization
State pattern
characteristics
Class Diagram
concept
connection issues
contexts, method parameters
Directed Graph Document
GoF definition
implementation
job-processing system
Output
pros and cons
real-world scenario
Solution Explorer View
Strategy pattern
abstract class
advantages
challenges
Class Diagram
concept
default behavior
Directed Graph Document
GoF definition
implementation
inheritance mechanism
Output
Solution Explorer View
Static initialization
Template Method pattern
advantages
BasicEngineering class
challenges
Class Diagram
concept
GoF definition
implementation
Modified Output
Modified Program
Output
Solution Explorer View
Visitor pattern
Class Diagram
Composite pattern
implementation
Output
Solution Explorer View
tree structure
concept
drawbacks
encapsulation
GoF definition
implementation
Output
public APIs
Solution Explorer View
Windows Presentation Foundation (WPF)
3.15.214.155