Design Pattern Module 1
Design Pattern Module 1
Introduction
What Is a Design Pattern?
• 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.
• In general, a pattern has four essential elements
• The pattern name is a handle we can use to describe a
design problem, its solutions, and consequences in a word
or two. Naming a pattern immediately increases our
design vocabulary.
• The problem describes when to apply the pattern. It
explains the problem and its context.
• The solution describes the elements that make up the
design, their relationships, responsibilities, and
collaborations.
• The consequences are the results and trade-offs of
applying the pattern. Though consequences are often
unvoiced when we describe design decisions, they are
critical for evaluating design alternatives and for
understanding the costs and benefits of applying the
pattern.
Design Patterns in Smalltalk
MVC
• Looking at the design patterns inside MVC should help
you see what we mean by the term “pattern.”
• MVC consists of three kinds of objects. The Model is the
application object, the View is its screen presentation,
and the Controller defines the way the user interface
reacts to user input.
• Before MVC, user interface designs tended to lump these
objects together. MVC decouples them to increase
flexibility and reuse.
• MVC decouples views and models by establishing a
subscribe/notify protocol between them.
• A view must ensure that its appearance reflects the state
of the model.
• Whenever the model’s data changes, the model notifies
views that depend on it. In response, each view gets an
opportunity to update itself. This approach lets you attach
multiple views to a model to provide different
presentations. You can also create new views for a model
without rewriting it.
• But the design is applicable to a more general problem:
decoupling objects so that changes to one can affect any
number of others without requiring the changed object to
know details of the others.
• Another feature of MVC is that views can be nested.
• MVC also lets you change the way a view responds to user
input without changing its visual presentation.
• You might want to change the way it responds to the
keyboard, for example, or have it use a pop-up menu
instead of command keys.
• MVC encapsulates the response mechanism in a
Controller object. There is a class hierarchy of controllers,
making it easy to create a new controller as a variation on
an existing one.
• A view uses an instance of a Controller subclass to
implement a particular response strategy; to implement a
different strategy, simply replace the instance with a
different kind of controller.
• It’s even possible to change a view’s controller at run-time
to let the view change the way it responds to user input.
• The View-Controller relationship is an example of the
Strategy design pattern.
• A Strategy is an object that represents an algorithm. It’s
useful when you want to replace the algorithm either
statically or dynamically, when you have a lot of variants
of the algorithm, or when the algorithm has complex data
structures that you want to encapsulate.
• MVC uses other design patterns, such as Factory Method
to specify the default controller class for a view and
Decorator to add scrolling to a view. But the main
relationships in MVC are given by the Observer,
Composite, and Strategy design patterns.
• Design patterns are basically defined as reusable solutions
to the common problems that arise during software design
and development.
• They are general templates or best practices that guide
developers in creating well-structured, maintainable, and
efficient code.
• Singleton Pattern
• The Singleton method or Singleton Design pattern is one of the
simplest design patterns. It ensures a class only has one
instance, and provides a global point of access to it.
• Factory Method Pattern
• The Factory Method pattern is used to create objects without
specifying the exact class of object that will be created. This
pattern is useful when you need to decouple the creation of an
object from its implementation.
• Abstract Factory Pattern
• Abstract Factory pattern is almost similar to Factory Pattern and is
considered as another layer of abstraction over factory pattern.
Abstract Factory patterns work around a super-factory which creates
other factories.
• Builder Pattern
• Builder pattern aims to “Separate the construction of a complex object
from its representation so that the same construction process can
create different representations.” It is used to construct a complex
object step by step and the final step will return the object.
• Prototype Pattern Prototype allows us to hide the complexity of
making new instances from the client.
• The concept is to copy an existing object rather than creating a new
instance from scratch, something that may include costly operations. The
existing object acts as a prototype and contains the state of the object.
• Adapter Pattern
• The adapter pattern convert the interface of a class into
another interface clients expect. Adapter lets classes work
together that couldn’t otherwise because of incompatible
interfaces
• Bridge Pattern
• The bridge pattern allows the Abstraction and the
Implementation to be developed independently and the
client code can access only the Abstraction part without
being concerned about the Implementation part.
• Composite Pattern
• Composite pattern is a partitioning design pattern and describes a group of
objects that is treated the same way as a single instance of the same type of
object. The intent of a composite is to “compose” objects into tree structures
to represent part-whole hierarchies.
• Decorator Pattern
• It allows us to dynamically add functionality and behavior to an object
without affecting the behavior of other existing objects within the same class.
• We use inheritance to extend the behavior of the class. This takes place at
compile-time, and all the instances of that class get the extended behavior.
• Facade Pattern
• Facade Method Design Pattern provides a unified interface to a set of
interfaces in a subsystem. Facade defines a high-level interface that makes
the subsystem easier to use.
• Proxy Pattern
• Proxy means ‘in place of’, representing’ or ‘in place of’ or ‘on behalf of’ are
literal meanings of proxy and that directly explains Proxy Design Pattern.
• Proxies are also called surrogates, handles, and wrappers. They are closely
related in structure, but not purpose, to Adapters and Decorators.
• Flyweight Pattern
• This pattern provides ways to decrease object count thus improving
application required objects structure. Flyweight pattern is used when
we need to create a large number of similar objects.
• Observer Pattern
• It defines a one-to-many dependency between objects, so that when one
object (the subject) changes its state, all its dependents (observers) are
notified and updated automatically.
• Strategy Pattern
• that allows the behavior of an object to be selected at runtime. It is one
of the Gang of Four (GoF) design patterns, which are widely used in
object-oriented programming.
• The Strategy pattern is based on the idea of encapsulating a family of
algorithms into separate classes that implement a common interface.
• Command Pattern
• The Command Pattern is a behavioral design pattern that turns a request into
a stand-alone object, containing all the information about the request. This
object can be passed around, stored, and executed at a later time
• Chain of Responsibility Pattern
• Chain of responsibility pattern is used to achieve loose coupling in software
design where a request from the client is passed to a chain of objects to
process them.
• Later, the object in the chain will decide themselves who will be processing
the request and whether the request is required to be sent to the next object
in the chain or not.
• State Pattern
• A state design pattern is used when an Object changes its behavior
based on its internal state. If we have to change the behavior of an object
based on its state, we can have a state variable in the Object and use the
if-else condition block to perform different actions based on the state.
• Template Method Pattern
• Template method design pattern is to define an algorithm as a skeleton of
operations and leave the details to be implemented by the child classes.
The overall structure and sequence of the algorithm are preserved by the
parent class.
• Visitor Pattern
• It is used when we have to perform an operation on a group of similar kind
of Objects. With the help of visitor pattern, we can move the operational
logic from the objects to another class.
• Interpreter Pattern
• Interpreter pattern is used to defines a grammatical representation for a
language and provides an interpreter to deal with this grammar.
• Mediator Pattern
• It enables decoupling of objects by introducing a layer in between so that
the interaction between objects happen via the layer.
• Memento Pattern
• It is used to restore state of an object to a previous state. As your
application is progressing, you may want to save checkpoints in your
application and restore back to those checkpoints later.
• Intent of Memento Design pattern is without violating encapsulation,
capture and externalize an object’s internal state so that the object
can be restored to this state later.
How Design Patterns Solve Design
Problems
Specifying Object
Implementation
• Finding Appropriate Objects
• Requests are the only way to get an object to execute an operation.
Operations are the only way to change an object’s internal data. Because of
these restrictions, the object’s internal state is said to be encapsulated; it
cannot be accessed directly, and its representation is invisible from outside
the object.
• The hard part about object-oriented design is decomposing a system into
objects. The task is difficult because many factors come into play:
encapsulation, granularity, dependency, flexibility, performance, evolution,
reusability, and on and on. They all influence the decomposition, often in
conflicting ways
• For example, the Composite pattern introduces an
abstraction for treating objects uniformly that doesn’t
have a physical counterpart.
• The Strategy pattern describes how to implement
interchangeable families of algorithms.
• The State pattern represents each state of an entity as
an object
• Determining Object Granularity
• Objects can vary tremendously in size and number. They can
represent everything down to the hardware or all the way up to
entire applications. How do we decide what should be an object?
• Design patterns address this issue as well.
• The Facade pattern describes how to represent complete
subsystems as objects, and the Flyweight pattern describes how to
support huge numbers of objects at the finest granularities.
• Other design patterns describe specific ways of decomposing an
object into smaller objects.
• Abstract Factory and Builder yield objects whose only
responsibilities are creating other objects.
• isitor and Command yield objects whose only
responsibilities are to implement a request on another
object or group of object
• Specifying Object Interfaces
• An object’s interface characterizes the complete set of
requests that can be sent to the object. Any request that
matches a signature in the object’s interface may be sent
to the object.
s
• When a request is sent to an object, the particular
operation that’s performed depends on both the request
and the receiving object. Different objects that support
identical requests may have different implementations of
the operations that fulfill these requests. The run-time
association of a request to an object and one of its
operations is known as dynamic binding.
• Design patterns help you define interfaces by identifying their key
elements and the kinds of data that get sent across an interface. A
design pattern might also tell you what not to put in the interface.
• The Memento pattern is a good example. It describes how to
encapsulate and save the internal state of an object so that the object
can be restored to that state later. The pattern stipulates that
Memento objects must define two interfaces: a restricted one that
lets clients hold and copy mementos, and a privileged one that only
the original object can use to store and retrieve state in the
memento.
• Design patterns also specify relationships between interfaces.
• In particular, they often require some classes to have similar
interfaces, or they place constraints on the interfaces of some
classes.
• For example, both Decorator and Proxy require the interfaces
of Decorator and Proxy objects to be identical to the decorated
and proxied objects.
• In Visitor, the Visitor interface must reflect all classes of objects
that visitors can visit.
• Specifying Object Implementations
• For example, objects in a Chain of Responsibility must
have a common type, but usually they don’t share a
common implementation.
• In the Composite pattern, Component defines a common
interface, but Composite often defines a common
implementation.
• Command , Observer , State , and Strategy are often
implemented with abstract classes that are pure
interfaces.
• The State , Strategy , and Visitor patterns depend on it.
• In the State pattern, an object delegates requests to a State object that
represents its current state.
• In the Strategy pattern, an object delegates a specific request to an
object that represents a strategy for carrying out the request. An object
will only have one state, but it can have many strategies for different
requests. The purpose of both patterns is to change the behavior of an
object by changing the objects to which it delegates requests.
• In Visitor, the operation that gets performed on each element of an
object structure is always delegated to the Visitor object.
Selecting a Design Pattern
• Consider how design patterns solve design problems
• Scan Intent sections
• Study how patterns interrelate
• Study patterns of like purpose.
• Examine a cause of redesign
• Consider what should be variable in your design
• Consider how design patterns solve design problems.
• How Design Patterns Solve Design Problems discusses
how design patterns help you find appropriate objects,
determine object granularity, specify object interfaces,
and several other ways in which design patterns solve
design problems.
• Referring to these discussions can help guide your search
for the right pattern.
• Scan Intent sections.
• Design Pattern Catalog lists the
Intent sections from all the
patterns in the catalog.
• Read through each pattern’s
intent to find one or more that
sound relevant to your problem.
You can use the classification
scheme presented in Table 1.1 to
narrow your search.
• Study how patterns
interrelate.