Brief History of Design Patterns
Brief History of Design Patterns
Design patterns have their roots in the work of Christopher Alexander, a civil engineer who
wrote about his experience in solving design issues as they related to buildings and towns. It occurred to
Alexander that certain design constructs, when used time and time again, lead to the desired effect. He
documented and published the wisdom and experience he gained so that others could benefit. About 15
years ago, software professionals began to incorporate Alexander's principles into the creation of early
design pattern documentation as a guide to novice developers.
Definitions:
Classification:
Most developers use informal patterns every day when writing code. Constructs such as
try...catch, using, and switch (Select Case) statements all follow standard patterns that developers have
learned over time. In fact, patterns can be:
Informal Design Patterns—such as the use of standard code constructs, best practice, well
structured code, common sense, the accepted approach, and evolution over time
Formal Design Patterns—documented with sections such as "Context", "Problem", "Solution",
and a UML diagram
Formal patterns usually have specific aims and solve specific issues, whereas informal patterns tend to
provide guidance that is more general.
Like Libraries and framework , Design patterns don’t go directly into your code, they first go into
your BRAIN.
Orgnizing Design Patterns:
Creational:
Behavioral
Structural
Design pattern documentation is highly structured. The patterns are documented from a
template that identifies the information needed to understand the software problem and the solution in
terms of the relationships between the classes and objects necessary to implement the solution. There
is no uniform agreement within the design pattern community on how to describe a pattern template.
Different authors prefer different styles for their pattern templates. Some authors prefer to be more
expressive and less structured, while others prefer their pattern templates to be more precise and high
grain in structure. We will use the template first described by the authors of Design Patterns to illustrate
a template.
Term Description
Pattern Name Describes the essence of the pattern in a short, but expressive, name
Intent Describes what the pattern does
Also Known As List any synonyms for the pattern
Motivation Provides an example of a problem and how the pattern solves that problem
Applicability Lists the situations where the pattern is applicable
Structure Set of diagrams of the classes and objects that depict the pattern
Participants Describes the classes and objects that participate in the design pattern and their
responsibilities
Collaborations Describes how the participants collaborate to carry out their responsibilities
Consequences Describes the forces that exist with the pattern and the benefits, trade-offs, and the
variable that is isolated by the pattern
This template captures the essential information required to understand the essence of the problem
and the structure of the solution. Many pattern templates have less structure than this, but basically
cover the same content.
Problem Definition:
To implement Duck Simulator, in which different types of duck can swim, fly or quack.
Requirements can change frequently as per client. There would be no limit for type of Duck.
Structure:
Term Description
Pattern Name Strategy Pattern
Intent It defines a family of algorithms, encapsulate each one, and makes them interchangeable.
Motivation Duck Simulator
Applicability Sorting Strategy,
Structure Class diagram on next slide
Class Diagram:
2. Observer Pattern:
Problem Definition:
To implement Weather Monitoring Application, in which provides three display
elements current conditions, weather statistics and simple forecast, all updated in real time
as WeatherData object acquire most recent measurements.
Structure:
Term Description
Pattern Name Observer Pattern
Intent It defines a one-to-many dependency between objects so that when one object changes
state, all of its dependents are modified and updated automatically.
Motivation Weather Monitoring Application
Applicability Stock exchange
Structure Class diagram on next slide
Class Diagram:
When an abstraction has two aspects, one dependent on the other. Encapsulating these
aspects in separate objects lets you vary and reuse them independently.
When a change to one object requires changing others, and you don't know how many
objects need to be changed.
When an object should be able to notify other objects without making assumptions about
who these objects are. In other words, you don't want these objects tightly coupled.
3. Decorator Pattern:
Problem Definition:
To implement Coffee shop to update their ordering system to match their beverage
offerings.
Structure:
Term Description
Pattern Name Decorator Pattern
Intent It attaches additional responsibility to an object dynamically. It provides flexible
alternative to subclassing for extending functionality.
Motivation Coffee shop
Applicability 'borrowable' functionality is added to existing library items (books and videos).
Structure Class diagram on next slide
Class Diagram:
Now let's assume we also wish the option to add borders to our windows. Again, our
original Window class has no support. The ScrollingWindow subclass now poses a
problem, because it has effectively created a new kind of window. If we wish to add
border support to all windows, we must create subclasses WindowWithBorder and
ScrollingWindowWithBorder. Obviously, this problem gets worse with every new
feature to be added. For the decorator solution, we need merely create a new
BorderedWindowDecorator—at runtime, we can decorate existing windows with the
ScrollingWindowDecorator or the BorderedWindowDecorator or both, as we see fit.
Another good example of where a decorator can be desired is when there is a need
to restrict access to an object's properties or methods according to some set of rules
or perhaps several parallel sets of rules (different user credentials, etc). In this case
instead of implementing the access control in the original object it is left unchanged
and unaware of any restrictions on its use, and it is wrapped in an access control
decorator object, which can then serve only the permitted subset of the original
object's interface.
[edit] Applicability
Consider viewing a webpage with a web browser. The webpage itself displays the
information needed, but the web browser knows nothing about the content. It is likely
that the webpage doesn't fit in the entire browser area and a scrollbar is required to
show the information. The web browser doesn't need to assume that all webpages
will require a scrollbar and it certainly should never assume a scrollbar is never
needed. Browsers will typically display the scrollbar only if it is necessary and hide it
if it is unnecessary. In this case, the scrollbar is the "decoration" to the webpage. It
takes care of whether it should be displayed dynamically as opposed to statically
forcing the webpage display to be a subclass of the scrollbar display. Thus, it is up
to the scrollbar to decide whether it should display itself (instead of trying to force
that responsibility on the webpage or on the external parts of the web browser).
Structure:
Term Description
Pattern Name Factory Method Pattern
Intent It defines an interface for creating an object , but lets subclasses decide which class to
instantiate.
Motivation Pizza shop
Applicability Creating different IO files in system.
Structure Class diagram on next slide
Class Diagram:
5. Singleton Pattern:
Problem Definition:
To implement Chocolate boilers to take in chocolate and milk, bring them to a boil, and
then pass them on to next phase of making chocolate bar. We have to take care of not filling
boiler when it is already full.
Structure:
Term Description
Pattern Name Singleton Pattern
Intent It ensures a class has only one instance, provide a global point of access to it.
Motivation Chocolate Boiler
Applicability Registry Setting
Class Diagram:
6. Command Pattern:
Problem Definition:
To design Home automation Remote Control which features some slots along with
corresponding on/off buttons. Remote also has a global undo button.
Structure:
Term Description
Pattern Name Command Pattern
Intent It encapsulates a request as an object, thereby letting you parameterize other objects with
different requests and support undoable operations.
Motivation Home automation Remote Control
Applicability simple calculator with unlimited number of undo's and redo's
Class Diagram:
Multi-level undo
If all user actions in a program are implemented as command objects, the
program can keep a stack of the most recently executed commands. When
the user wants to undo a command, the program simply pops the most recent
command object and executes its undo() method.
Transactional behavior
Undo is perhaps even more essential when it's called rollback and happens
automatically when an operation fails partway through. Installers need this
and so do databases. Command objects can also be used to implement two-
phase commit.
Progress bars
Suppose a program has a sequence of commands that it executes in order. If
each command object has a getEstimatedDuration() method, the program
can easily estimate the total duration. It can show a progress bar that
meaningfully reflects how close the program is to completing all the tasks.
Wizards
Often a wizard presents several pages of configuration for a single action that
happens only when the user clicks the "Finish" button on the last page. In
these cases, a natural way to separate user interface code from application
code is to implement the wizard using a command object. The command
object is created when the wizard is first displayed. Each wizard page stores
its GUI changes in the command object, so the object is populated as the
user progresses. "Finish" simply triggers a call to execute(). This way, the
command class contains no user interface code.
GUI buttons and menu items
In Swing and Borland Delphi programming, an Action is a command object. In
addition to the ability to perform the desired command, an Action may have
an associated icon, keyboard shortcut, tooltip text, and so on. A toolbar button
or menu item component may be completely initialized using only the Action
object.
Thread pools
A typical, general-purpose thread pool class might have a public addTask()
method that adds a work item to an internal queue of tasks waiting to be
done. It maintains a pool of threads that execute commands from the queue.
The items in the queue are command objects. Typically these objects
implement a common interface such as java.lang.Runnable that allows the
thread pool to execute the command even though the thread pool class itself
was written without any knowledge of the specific tasks for which it would be
used.
Macro recording
If all user actions are represented by command objects, a program can record
a sequence of actions simply by keeping a list of the command objects as
they are executed. It can then "play back" the same actions by executing the
same command objects again in sequence. If the program embeds a scripting
engine, each command object can implement a toScript() method, and user
actions can then be easily recorded as scripts.
Networking
It is possible to send whole command objects across the network to be
executed on the other machines, for example player actions in computer
games.
Parallel Processing
Where the commands are written as tasks to a shared resource and executed
by many threads in parallel (possibly on remote machines -this variant is often
referred to as the Master/Worker pattern)
Mobile Code
Using languages such as Java where code can be streamed/slurped from one
location to another via URLClassloaders and Codebases the commands can
enable new behavior to be delivered to remote locations (EJB Command,
Master Worker)
7. Adaptor Pattern:
Problem Definition:
In Duck simulator (developed in Strategy Pattern) we are short on Duck object and you’d
like to use some Turkey object in their place as a Duck object. Obviously we can’t use Turkey
totally as they have different interface.
Structure:
Term Description
Pattern Name Adaptor Pattern
Intent It converts the interface of a class into another interface the client expect. Adaptor lets
classes work together that could not otherwise because of incompatible interfaces.
Motivation Duck Simulator
Applicability Work with new vendor Class library which is designed their interfaces differently than the
last vendor.
Class Diagram:
8. Facade Pattern:
Problem Definition:
Watching a movie – Pick out a DVD, relax and get ready for movie magic. Oh, to watch
movie, you need to perform following tasks:
a. Dim the lights
b. Put the screen down
c. Turn the projector on
d. Set the projector input to DVD
e. Put the projector on wide-screen mode
f. Turn the sound amplifier on
g. Set the amplifier to DVD input
h. Turn the DVD player on
i. Start the DVD player playing
Structure:
Term Description
Pattern Name Facade Pattern
Intent It provides a unified interface to set of interfaces in a subsystem. It defines a higher level
interface that makes the subsystem easier to use.
Motivation To Watch Movie
Applicability VB.Net IDE
Class Diagram:
make a software library easier to use and understand, since the facade has
convenient methods for common tasks;
make code that uses the library more readable, for the same reason;
reduce dependencies of outside code on the inner workings of a library, since
most code uses the facade, thus allowing more flexibility in developing the
system;
wrap a poorly designed collection of APIs with a single well-designed API (As
per task needs).
Structure:
Term Description
Pattern Template Method Pattern
Name
Intent It defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It
lets subclasses redefine certain steps of an algorithm without changing the algorithm’s
structure.
Motivation Tea-coffee Training Manual
Applicability Dot Net Framework, Sorting etc.
Class Diagram:
Structure:
Term Description
Pattern Name Iterator Pattern
Intent It provides a way to access the elements of an aggregate object sequentially without
exposing its underlying representation.
Motivation Menu Printing
Applicability Collection
Problem Definition:
To implement machine which has 4 states and corresponding 4 actions. There can be 1
or more actions per state. States can be increased in future.
Structure:
Term Description
Pattern Name State Pattern
Intent It allows an object to alter its behavior when its internal state changes. The object will
appear to change its class.
Motivation Machine implementation
Applicability Collection
Class Diagram:
Summary: