0% found this document useful (0 votes)
77 views42 pages

design patterns sem 2 mca final pdf

The document outlines various design patterns, including Factory Method, Abstract Factory, Singleton, Builder, Prototype, Object Pool, Adapter, Bridge, and Composite, each serving distinct purposes in software design. It describes the components and workflows of each pattern, emphasizing their utility in creating flexible and maintainable code. Real-world examples illustrate how these patterns can be applied to solve common programming challenges.
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
0% found this document useful (0 votes)
77 views42 pages

design patterns sem 2 mca final pdf

The document outlines various design patterns, including Factory Method, Abstract Factory, Singleton, Builder, Prototype, Object Pool, Adapter, Bridge, and Composite, each serving distinct purposes in software design. It describes the components and workflows of each pattern, emphasizing their utility in creating flexible and maintainable code. Real-world examples illustrate how these patterns can be applied to solve common programming challenges.
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/ 42

Factory Method

Creational pattern

Factory Method allows us to create objects from an specific subtype through a


Factory class. This is especially useful when we don't know which subtype we are
going to use at design-time, or when do we want to delegate object creation logic
to a Factory class. Using this pattern we can dynamically create instances by
writing implementation settings on a text file, a XML file, on properties, or using
any other strategy.

These are the components included in the pattern:

 IProduct: It represents, in an abstract manner, the object we want to create. This


interface is used for defining the structure of the object.
 ConcreteProduct: It represents the concrete implementation of the IProduct
interface, which is created by the ConcreteFactory.
 AbstractFactory: This component is optional, however, it would be recommendable
to create an AbstractFactory for defining the default behavior of the
ConcreteFactory.
 Concrete Factory: It is used for creating the ConcreteProduct, this class inherits its
behavior from the AbstractFactory.
1. The client requests ConcreteFactory for the creation of ProductA .
2. ConcreteFactory finds the concrete implementation of ProductA and creates a
new instance.
3. ConcreteFactory returns a new ConcreteProductA .
4. The client requests ConcreteFactory for the creation of ProductB.
5. ConcreteFactory finds the concrete implementation of ProductB and creates a
new instance.
6. ConcreteFactory returns a new ConcreteProductB .
 Real-world example
 By implementing the Factory Method design pattern, we are going to create an
application capable of connecting with one or more databases, and switching from
one to other only by changing settings and without having to write additional lines
of code.

Abstract Factory
Creational pattern

The goal of the Abstract Factory design pattern is to form a group of classes with
shared functionalities, better known as families, created by a Factory. This pattern
is especially useful when we need to implement certain class families to solve a
problem, however, we may need to add parallel implementations of the same
classes to solve the same problem with a different approach.
The structure of Abstract Factory may look quite convoluted since it has many
components which seem to intertwine with each other. To better explain how this
pattern works, let's review its components one by one:

 Client: It represents the actor or event which triggers the execution of the pattern.
 AbstractProduct (A, B): Interfaces for defining the object structure of each family.
 ConcreteProduct (A, B): Classes that inherit their properties from AbstractProduct for
implementing entire families of concrete objects.
 ConcreteFactory: They represent the concrete factories that will create instances of all the
classes of the family. This class must have a method for creating each and every one of
the classes of the family.
 AbstractFactory: They define the structure of the families. They must provide a method for
each and every one of the classes of the family.

1. The client sends a request to AbstractFactory al ConcreteFactory1 .


2. The AbstractFactory creates an instance of ConcreteFactory1 and returns it.
3. The client sends a request to ConcreteFactory1 for the creation of ProductA .
4. The ConcreteFactory1 creates an instance of ProductA1 which is a member of
family1, and returns it.
5. Now the client sends a request to AbstractFactory al ConcreteFactory2 .
6. The AbstractFactory creates an instance of ConcreteFactory2 .
7. The client sends a request to ConcreteFactory2 for the creation of ProductA .
8. The ConcreteFactory2 creates an instance of ProductA2 which is a member of
Family2, and returns it.
Real-world example
By implementing theAbstract Factory design pattern, we are going to develop an
application for communicating with a Backend system via Web Services and
REST, in order to give the client the option to use any of these methods by
configuration.

Singleton
Creational pattern

The Singleton design pattern receives this name because it can only have a single
instance of a specific class for the entire application; this is achieved by preventing
the creation of multiple instances of the same class, as it typically happens with the
new operator, and imposing a private constructor and a static method to get that
instance.

The objective of this pattern is to guarantee the creation of a single instance of a


specific class and the existence of a global reference for the entire application.

Google Translator is an example of the interpreter design pattern where the input can be in any language and
we get the output in another language.
These are the components included in this pattern:

 Client: It's the component requesting an instance of the Singleton class.


 Singleton: It's the class implementing the Singleton pattern, from which only one
instance can exist during the entire life-cycle of the application.

1. The client requests for an instance of the Singleton through the


getInstancemethod.
2. The Singleton checks if the instance has already been created, if not, a new
instance will be created.
3. Either the newly created instance or the already existing instance is
returned.

Real-world example

By implementing the Singleton design pattern, we are going to create an


application for managing the system settings from a sole central point. Therefore,
when the application starts, the initial settings will be loaded up and stay available.
Builder
Creational pattern

This is a pretty simple but very useful pattern, which allows us to create a complex
object from simpler ones. It is very common to find ourselves in situations where
we need to manually create complex objects over and over again, which lead us to
assign properties to each and every one of them, and if such objects have to be
built from some other objects, then we need to create those first in order to assign
them to the main one we’re building. It is a long and tedious process, especially
when it needs to be done frequently.

These are the components included in this pattern:

 IBuilder: The use of this component is not mandatory, however, it is


recommended for specifying a common interface for all the Builder objects we're
going to define in our application. It could be an interface for only defining a build
method.
 ObjectBuilder: This is the class we’ll use for creating the TargetObject. This class
should inherit from IBuilder and implement the build method, which is going to be
used for creating the TargetObject. As a general rule, all the methods in this class
return an instance of themselves in order to speed up the creation process.
Usually, they are created as internal classes of TargetObject.
 TarjetObjet: It represents the object we want to create with the aid of the
ObjectBuilder, this can be a simple class or a complex class containing many
objects.
 OtherObjets: They represent the objects we may create when the ObjectBuilder
builds the TargetObject.
1. The client creates an instance of the ObjectBuilder .
2. The client executes step 1 in the ObjectBuildercreation.
3. Internally, TargetObject is created by the ObjectBuilder.
4. The client executes step 2 in the ObjectBuildercreation.
5. Internally, OtherObjectA is created by the ObjectBuilder.
6. The client executes step 3 in the ObjectBuildercreation.
7. Internally, OtherObjectB is created by the ObjectBuilder.
8. The client requests ObjectBuilder for the creation of the TargetObject, this
takes all the previously created objects, assigns them to TargetObject and
returns them.
Real-world example

By implementing the Builder design pattern, we are going to solve a classic


problem, that is, building a complex object with the aid of a Builder class, which will
allow us to create the entire structure of an employee, along with all of its
information, such as address, phone numbers, contacts, etcetera.

PROTOTYPE
Creational pattern

The Prototype pattern functionality is based on object cloning. New objects are
created from a pool of previously created and stored prototypes. This pattern is
especially useful when we need to create objects from existing ones or for creating
very large structures of objects. This pattern also helps us hide the strategy we
used for cloning objects from the user.
The components included in this pattern are:

 Client: The component which interacts with the prototypes.


 IPrototype: This component is typically an interface which defines the minimum
attributes of a prototype. This interface should have at least one of these two
cloning types: Shallow cloning (clone) or Deep cloning (deepClone) which will be
explained later.
 ConcretePrototype: Concrete implementations of the IPrototype objects, which
can be cloned.
 PrototypeFactory: This is the component we will use for keeping a cache of
existing prototypes in order to make clones from them.

Real-world example

By implementing the Prototype design pattern, we are going to clone an entire list
of products in order to create others from it. How many times have we seen
companies working with more than one price list, which must be created from
scratch and then filled up with the same products from the original? Wouldn't it be
better to use a price list as a template for creating new lists with different
discounts?

Object Pool
Creational pattern

This pattern is widely used for working with large numbers of computationally
expensive objects. This pattern is advantageous for those scenarios where our
program needs these kinds of objects for a short time to discard them afterwards.
This pattern allows us to reutilize objects to keep us from having to create them
each time our application requires them, by storing previously created objects in
order to be used later.
The components included in this pattern are:

 IObjectPool: Interface which defines the basic structure of an Object Pool, it has the get
and release methods which will be used for getting and releasing objects, respectively.
 AbstractObjectPool: Abstract class which defines the default behavior of an Object Pool,
this class can be used as a basis for creating a ConcreteObjectPool more quickly.
 ConcreteObjectPool: It is the complete, and ready-to-be-used, implementation of an
Object Pool.
 IPoolableObject: Interface which should implement all the objects we want to manage
through ObjectPool. With this interface we can define the basic structure all objects should
have.
 ConcretePoolableObject: These are the real objects to be managed by ObjectPool, they
should inherit from IPoolableObject.
 IObjectFactory: Interface which will define the structure of the ConcretePoolableObject
factory.
 ConcreteObjectFactory: Concrete factory which implements IObjectFactory for the
creation of a ConcretePoolableObject.
1. The client sends a request for an object to ConcreteObjectPool .
2. ConcreteObjectPool checks if the required object is available, otherwise it will send the request for
the creation of a new object to ConcreteObjectFactory.
3. ConcreteObjectFactory creates a new object whose type is ConcretePoolableObject.
4. ConcreteObjectPool returns the object to the client.
5. The client uses the object.
6. The client returns the object to ConcreteObjectPool.

Real-world example

By implementing the Object Pool design pattern, we are going to develop a multi-
threaded application, which has to carry out many tasks simultaneously. The
Object Pool will control how many processes can be executed at the same time, by
setting a maximum limit in order to avoid running out of resources and to maintain
an even performance throughout the execution, keeping the rest of the processes
in a queue to be executed whenever it's allowed.

Adapter
Structural pattern

The Adapter design pattern is used when we encounter incompatible software


interfaces, which, even with this inherent incompatibility, have similar features.
This pattern is used when we want to work with different interfaces in a
homogeneous manner, to that end, we create an intermediate class which
functions as an adapter. This adapter class will provide the methods needed for
interacting with the incompatible interface.
The components included in this pattern are:

 Client: The actor interacting with the Adapter.


 Target: Interface for homogenizing the manner in which we’re going to work with
the incompatible interfaces. This interface is used for creating the Adapters.
 Adapter: It represents the implementation of the Target, which has the
responsibility of mediating between the Client and the Adaptee. It hides the
communication method with the Adaptee.
 Adaptee: It represents the class with the incompatible interface.

1. The Client invokes the Adapter with generic parameters.


2. The Adapter converts the generic parameters into specific parameters for the
Adaptee.
3. The Adapter invokes the Adaptee.
4. The Adaptee answers the call.
5. The Adapter converts the response of the Adaptee into a generic response for the
Client.
6. The Adapter attends the Client with a generic response.

Real-world example

By implementing the Adapter design pattern, we are going to create an adapter for
interacting homogeneously with two Bank APIs, both of which allow us to approve
personal loans. However, even though these APIs work similarly, they have
different interfaces, which means that we need to set separate implementations in
order to process the loans through each bank. With this pattern, we will create an
adapter for hiding the intricacies of each API implementation, by showing only a
single interface, compatible with both APIs.

Bridge
Structural pattern

The Bridge design pattern is used for decoupling an abstraction from its
implementation, the purpose is that each one can be modified separately without
affecting the other; in other words, an abstraction gets decoupled from its
implementation so they can vary independently.

The Bridge pattern is mostly used when we have two related pieces of software
and there’s a high probability that modifying one of them can lead to have the other
modified too. What Bridge proposes to solve this problem is creating a class
structure based on aggregation, which includes a bridge class for decoupling the
class we want to use from the client, so the latter can’t be aware of the former, in a
way that one can change without affecting the other.

The components of this pattern are:


 Abstraction: Interface for defining the structure of the bridge class.
 AbstractionImpl: Class used as a bridge for decoupling Abstraction from Implementor.
This class inherits from Abstraction.
 Implementor: It defines a common class structure for all the ConcreteImplementor. This
interface isn’t strictly required for implementing the pattern.
 ConcreteImplementor: Class group which inherits from Implementor and is subject to
changes, the reason why we are using the Bridge design pattern.

1. The client executes an AbstraccionImploperation.


2. AbstraccionImpl relays this petition to ConcreteImplementor, at this point AbstraccionImpl
can convert the parameters needed for executing the ConcreteImplementor.
3. ConcreteImplementor returns the results to AbstraccionImpl.
4. The AbstraccionImpl converts the results coming from ConcreteImplementor to give them
to the client.

Real-world example

By implementing the Bridge we are going to create an application that allows us to


communicate with an external system, this communication must by encrypted
using different algorithms. However, the concrete implementation of the encryption
algorithm may change, which means that we need to create an adapter for
decoupling this concrete implementation from the handling method, which is why
we will use an adapter for encapsulating the inner logic and to provide a single
interface for all the encryption methods.
Composite
Structural pattern

The Composite design pattern helps us constructing complex structures from


simpler ones; in other words, we can use small structures to assemble a bigger
and more complex structure.

The pattern's components are:

 Component: It usually is an interface or abstract class including the basic


operations which will be used. This component should be extended by the other
two components: Leaf and Composite.
 Leaf: It represents the smaller or simpler part of the entire structure, which inherits
from Component. It's named after the tree theory, in which any node with no
descendant receives such name. In this case, they are simple classes that haven't
been built from others.
 Composite: This component is the one bringing life to this pattern, because it's
built from a group of Components and Leafs. In tree theory, this component would
represent a branch.
1. El cliente realizar una acción sobre el CompositeA.
2. CompositeA a su vez realiza una acción sobre CompositaB.
3. CompositeB realiza una acción sobre LeafA y LeafB y el resultado es devuelto a
CompositeA.
4. CompositeA propaga la acción sobre LeafC, el cual le regresa un resultado.
5. CompositeA obtiene un resultado final tras la evaluación de toda la estructura y el cliente
obtiene un resultado.

Real-world example

By implementing the Composite design pattern, we are going to create an


application that allows us to build a complex structure of products, where a product
can either by just one single product or many products being represented as one.
These groups of products, or composite products, can also be created by grouping
many more composite products, all of them forming a tree structure where the
price of a product comes from the sum of all its nodes prices being interpreted by
the system as one single product.

Decorator
Structural pattern

The decorator pattern has been designed to solve scenarios where a


subclassification hierarchy cannot be applied, or when a great impact is required
over all the hierarchy classes in order to achieve the expected behavior. Decorator
allows the user to add new features to an existing object without altering its
structure through the addition of new classes wrapped around the original one,
giving it extra capabilities.
In the above illustration, we can see the all the components involved in the
Decorator design pattern, which I'll proceed to explain:

 IComponent: Interface defining the basic structure of the component or components to be


decorated.
 ConcreteComponent: IComponent implementation defining a concrete object which can
be decorated.
 ComponentDecorator: It usually is an abstract class defining the basic structure of a
Decorator, which should inherit from IComponent and contain some IComponent subclass
to be decorated.
 ComponentDecoratorImpl: Represents all the concrete decorators which inherit from
ComponentDecorator.
1. The Client executes an operation over DecoratorA.
2. The DecoratorA executes the same operation over DecoradorB.
3. The decoradorB executes an action over ConcreteComponent.
4. The DecoradorB executes a decoration operation.
5. The DecoradorA executes a decoration operation.
6. The Client receives a decorated object by all the Decorators, which
have encapsulated the Component below many layers.
Real-world example

By implementing the Decorator design pattern, we are going to develop an


application for processing a message through layers, where each layer will
process it on different levels. First, an object will be converted into XML, then, it's
going to be encapsulated into a SOAP message which will then be encrypted. At
the end, we're going to get a completely encrypted SOAP message which can be
securely sent to a recipient. Each processing layer will be implemented by a
decorator, and these decorators can swap positions to provide different results.
Also, more decorators can be added between other decorators.

Facade
Structural pattern

The Facade pattern has the particularity of hiding the complexity in interacting with
a group of subsystems by providing a high level interface, which is in charge of
establishing communication with all the subsystems. Using a facade is a good
strategy for interacting with multiple subsystems in order to execute a concrete
action, because we would need a technical and operational knowledge on each of
them to be aware of which subsystem we need to run and in which order, and that
can get too complicated when working with an overgrown system.
In the illustration, we can see the components included in the Facade pattern,
which are explained as follows:

 IFacade: Provides a high-level interface for hiding the complexity of


interacting with multiple systems to carry out an operation.
 Client: System or event which interacts with the facade.
 DefaultFacadeImpl: Represents the implementation of IFacade, which
is in charge of communicating with all the subsystems.
 Subsystems: Represents all the modules or subsystems with
interfaces for communication.
1. The client invokes a facadeoperation.
2. The facade communicates with SubsystemA to perform an operation.
3. The facade communicates with SubsystemB to perform an operation.
4. The facade communicates with SubsystemC to perform an operation.
5. The facade provides the client with the result of the operation.

Real-world example

By implementing the Facade design pattern, we are going to develop a system for
processing online payments, which would need to interact with different
subsystems, each of them bringing their own complexities. This can be a difficult
task, especially when we don't have information about the context of each
subsystem. For that reason, we will implement a facade to show high-level
operations that are going to be in charge of interacting with the subsystems,
abstracting us, the programmers, from dealing with the intricacies of these
interactions.

Flyweight
Structural pattern

Flyweight is a pattern dedicated to building light objects by abstracting parts that


can be reused and shared in order to create new objects when required, and
reusing objects created by other instances, significantly reducing the amount of
memory being used by the application.

This pattern is useful when resource optimization is fundamental, because it


eliminates redundancy on objects with identical properties.
The components included in the pattern are:

 Client: Object which triggers the execution.


 FlyweightFactory: Factory for building the Flyweight objects.
 Flyweight: It refers to the objects we want to reuse in order to create lighter objects.

1. The client requests the Factory for the creation of a Flyweightobject.


2. Before creating the object, the Factory checks if there's an identical object to the
one being requested, if so, it returns the existing object; if not, it will create the new
object and store it in a cache for further use.
3. The Flyweight object is created or borrowed from the cache and returned to the
client.

Real-world example

By implementing the Flyweight design pattern, we are going create an application


for managing playlists. Some songs must be shared between various playlists, and
some songs must have shared sections between them in order to save memory
space.
Proxy
Structural pattern

This pattern is devoted to the mediation between two objects. What I refer as
mediation is the series of actions executed before and after carrying out the task
requested by the user. The main trait of the Proxy pattern is that it keeps the user
unaware of the mediation that is being carried out in the background, because the
client receives an object structured as expected, all by interacting, unknowingly,
with a proxy.

The components included in the pattern are:

 IObject: It represents the common interface between the Object and the Proxy.
 Object: It represents the actual object the client wants access to.
 Proxy: Class which implements IObject and is the virtual representation of the
Object.
1. The client sends a request for an object to the Factory .
2. The Factory creates a Proxy for encapsulating the Object.
3. The client executes the Proxy which was created by the Factory.
4. The Proxy performs one or more actions before the execution of the Object.
5. The Proxy hands over the execution to the Object.
6. The Proxy performs one or more actions after the execution of the Object.
7. The Proxy returns the result.

Real-world example

By implementing the Proxy design pattern, we are going to create a security


mechanism that intercepts processes executions to check if the user attempting to
trigger them has the required privileges, in order to restrict unauthorized
executions. Furthermore, each executed process will be audited and registered. All
of this will happen without the user noticing, because the proxy would encapsulate
the security logic.
Iterator
Structural pattern

This design pattern allows us to go over a data structure without needing to know
its internal construction. It is especially useful when we are working with complex
data structures, because it lets us go over their elements through an iterator. The
iterator is an interface including the necessary methods for reviewing all the
elements of a data structure. The most common methods are:

 HASNEXT: This method returns a Boolean indicating if there are more


elements to be reviewed in the structure. It returns true if there still are
elements left and false if there are none left.
 NEXT: It returns the next element in the data structure.

The Iterator pattern elements are:

 Client: Actor using the iterator.


 Aggregate: Interface defining the class structures that can be iterated.
 ConcreteAggregate: Class containing the data structure we want to iterate.
 IIterator: Interface defining the iterator's structure, including the necessary
methods for performing the iteration over ConcreteAggregator.
 ConcreteIterator: It represents an iterator's concrete implementation, which will be
in charge of iterating the ConcreteAggregate data.
 The client sends a request for an iterator to ConcreteAggregate .

 ConcreteAggregate creates a new Iterator.

 The cliententers in a loop in order to review all the elements on the structure, the loop ends when there are no elements left for reviewing, which is going
to be signaled by the hasNext method.

 The client sends the request for a new element to the iterator using the nextmethod.

 If there are elements left to be reviewed, then we return to step 3, something that is going to be repeated until all elements have been reviewed.

Real-world example

By implementing the Iterator design pattern, we are going to create an application


that allows us to traverse a hierarchical organizational structure, by including an
iterator, which will go over the entire tree sequentially.
Command
Behavioral pattern

The Command design pattern allows us to execute operations without having to


know how they are implemented. These operations are known as commands, and
each operation is implemented as an independent class performing a very specific
action, which may or may not receive parameters in order to carry out its task. One
of the advantages offered by this pattern is the ability to create as many
commands as we need and encapsulate them into an execution interface.

The elements included in the Command pattern are:

 ICommand: Interface describing the structure of the commands, which defines the generic execution method for all of them.

 Concrete Command: They represent the concrete commands inheriting from ICommand. Each of these classes represents a command that can be
executed independently.

 Command Manager: This component lets us manage all the commands available at runtime, from here we're able to request commands or create new
ones.

 Invoker: It represents the action triggering one of the commands.

1. The invoker gets a command from CommandManager.

2. The invoker executes the command.

3. The invoker gets another command from CommandManager.

4. The invoker executes the command.


Real-world example

By implementing the Command design pattern, we are going to learn how to


create our own, entirely functional, console by developing a series of commands
that will be available for its use during the execution of the application.

Observer
Behavioral pattern

This design pattern allows us to observe the changes suffered by an object, that is,
if the observed object suffers any change, a notification will be sent to the
observers; this is known as publish-subscribe. Observer is one of the main design
patterns used in the development of graphical user interfaces (GUI), because it
allows us to decouple the graphical component from the action to be performed.

The components included in the pattern are:

 IObservable: Interface which must be implemented by all objects subject to observation, in it, all the basic implementable methods are defined.

 ConcreteObservable: This is the observable class; it implements IObservable along with its methods.

 IObserver: Interface which must be implemented by all objects in charge of observing the changes on IObservable.
 ConcreteObserver: Concrete class in charge of watching the changes on IObservable, it inherits from IObserver and must implement its methods.

 ObserverA registers into the Observable object in order to be notified of any changes.

 ObserverB registers into the Observable object in order to be notified of any changes.

 The status of the Observablechanges.

 All the Observers are notified that a change has occurred.

Real-world example

By implementing the Observer design pattern, we are going to develop an


application that loads the system configuration at the start. This configuration will
automatically notify all the observer objects of any changes that would happen in
order to let the user know about them. The purpose of this approach is to keep the
objects from having to constantly check for changes.
Template Method
Behavioral pattern

The template design pattern focuses on code reutilization for implementing steps
to solve problems. This is achieved by implementing base classes for defining
basic behaviors. Typically, methods are created for each step of the algorithm;
some of these will be implemented while others remain abstract until they are
executed by the subclasses.

The components included in the Template Method pattern are as follows:

 Client: It's the component which triggers the execution of the template.

 AbstractTemplete: It's an abstract class including a series of operations which define the necessary steps for carrying out the execution of the algorithm.
This class has a templateMethod method for executing step1, step2 and step3 in order.

 Implementation: This class represents a concrete template which inherits from AbstractTemplate and implements its methods.

1. The client creates and gets an instance of the template implementation.


2. The client executes the templateMethod .
3. The default implementation of templateMethod executes the step1, step2, step3methods
in order.
4. The template implementation returns a result.

Real-world example

By implementing the Templete Method design pattern, we are going to develop an


application for processing payment files. These files are generated by grocery
stores or convenience stores where the customers can pay services, such as
electricity, water, cable, internet, phone, etcetera. At the end of each day, these
stores would generate a plain text file to be sent to the respective companies in
order for them to process the payments. With the Template pattern, we will learn
how to process any type of file in a clear, simple and generic manner.

Strategy
Behavioral pattern

The strategy design pattern allows us to set the behavior of a class at runtime.
Strategy bases on polymorphism for implementing a series of behaviors that can
be interchanged during the execution of the program, allowing for a modification of
an object’s behavior by following a strategy that has been set.

The components included in this pattern are:


 Context: This component encapsulates the strategy to be used, which can be set at runtime.

 IStrategy: Common interface all strategies must implement. In it, all the operations the strategies need to implement are defined.

 ConcreteStrategy: It represents the concrete strategies, which inherit from IStrategy.

1. The client creates a new context and sets the StrategyA.

2. The client executes the doSomethingoperation.

3. Context hands over this responsibility to ConcreteStrategyA.

4. ConcreteStrategyA performs the operation and returns the result.

5. Context takes this result and hands it over to the client.

6. The client changes the Context strategy at runtime.

7. The client executes the doSomethingoperation again.

8. Context hands over this responsibility to ConcreteStrategyB.

9. ConcreteStategyB performs the operation and returns the result.

10. Context takes this result and hands it over to the client.

Real-world example

By implementing the Strategy design pattern, we are going to develop an


application that offers different authentication methods. User authentication will be
achieved via XML file, database or settings file in memory. With the Strategy
pattern, the user will be able to establish the preferred authentication method in the
application, without having to add any more code.
Chain of Responsability
Behavioral pattern

The Chain of Responsibility pattern stands out from others because of its
versatility, allowing us to solve problems where we’re not sure which object should
process a specific request; this design pattern can easily solve problems
inheritance can’t because of its chain structure, where a series of objects try to
process a request in sequence.

The components included in the pattern are:

 Client: User or system triggering the execution of the pattern.

 AbstractHandler: Base class used for defining the structure of every ConcreteHandler. This class is an aggregation of itself, which allows it to contain
another AbstractHandler for carrying on with the execution chain.

 ConcreteHandler: It represents the concrete implementation of an AbstractHandler.


1. The client sends a request to the chain of responsibility for its processing.

2. The first Handler tries to process the request but it’s unable to do it, therefore, it relays the request to the next handler .

3. The second Handler tries to process the request but it’s unable to do it, therefore, it relays the request to the next Handler .

4. The third Handler tries to process the request but it’s unable to do it, therefore, it relays the request to the next Handler .

5. The HandlerN (Any handler in the chain) is the one finally succeeding in processing the request, after which it sends a response (optional) so it can be
relayed by all the previous Handlers until it reaches to the Client.

Real-world example

By implementing the Chain of Responsability design pattern, we are going to


implement an order validation system. When we work with ERP or CRM systems,
it's fairly common to manage almost everything through orders, being sales,
purchases, services and installations. These orders are highly complex objects
compounded by a lot of other objects, such as customers, providers, products,
etcerera. These systems must check the completion of an order, and that all of the
information they carry is valid to the type of order being processed. To that end, we
will use the Chain of Responsability pattern and create an effective mechanism for
validating any type of order, by reusing validators between these different types.

Interpreter
Behavioral pattern

The Interpreter design pattern is used for evaluating a determined language and
return an Expression. This pattern can interpret languages such as Java, C#, SQL,
or even a new one invented by us, and provide a response based on its
evaluation.

This is one of the most complex design patterns, because we need to combine
various object-oriented programming techniques in order to implement it, which
can make it a bit difficult to understand. The main techniques we're going to be
dealing with are Inheritance, Polymorphism and Recursivity.
The components included in the Interpreter pattern are as follows:

 Client: Actor triggering the execution of the interpreter.

 Context: Object carrying global information to be used by the interpreter in order to read and store information of all the classes in the pattern. This
object is sent to the interpreter which then relays it to the rest of the structure.

 AbstractExpression: Interface for defining the basic structure of an expression.

 TerminalExpression: It refers to expressions which, after being evaluated or interpreted, end the execution of a branch or subtree.

 NonTerminalExpression: These are composite expressions, which contain more expressions subject to evaluation. They are interpreted by using
recursivity until a terminal expression is found.

1. The client creates the context for the execution of the interpreter.

2. The client creates or gets the expression to be evaluated.

3. The client requests for the evaluation of the expression to the interpreter . To that end, it sends it the context.

4. The Expression calls the Non-terminal Expressions .

5. The Non-terminal Expressions call all the Terminal Expressions.

6. The Root Expression requests for the interpretation of a Terminal Expression.

7. The Expression is completely evaluated and provides the result of the interpretation of all the Terminal Expressions and Non-terminal Expressions.
Real-world example

By implementing the Interpreter design pattern, we are going to build an


application capable of interpreting SQL commands to send queries to an Excel file,
as if it were a relational database, where each sheet would be seen as a chart, and
the columns of that sheet would be seen as the columns of a chart. To that end,
we will build our own class structure for representing the SQL language, in order to
be then interpreted and provide a result.

Google Translator is an example of the interpreter design pattern where the input can be in any
language and we get the output in another language.

Mediator
Behavioral pattern

The Mediator design pattern handles the manner in which a group of classes
interact with each other. This pattern is especially useful when we have a large
number of classes communicating directly with one another. By implementing this
pattern, we can create a bidirectional communication layer, which can be used by
a class in order to interact with others through a common object acting as a
mediator.

One of the main problems we face when building large projects is that the number
of classes can grow even larger and increase the interactions and relationships
between them. This can bring issues with coupling, especially when we're creating
direct communication channels which can be hard to track and debug.
The components included in the pattern are:

 Client:Component for starting the communication with the rest of the components through the mediator.

 Components:These are parts of the mediator communication network, that is, diverse objects sharing the same mediator for communicating with each
other.

 Mediador:Component for handling the communication between the rest of the components. It directs the incoming messages to the corresponding
receiver.

1. ComponentA wants to communicate with ComponentB and sends a message through the mediator.

2. The mediator may analyze the message for debugging or tracking purposes, or for directing it to the receiver.

3. The message is delivered to the receiver, which in turn sends a response to the mediator.

4. The mediator receives the response and directs it to ComponentA.


5. Likewise, the process can go in reverse, from ComponentB to ComponentA by repeating the previous steps in order to achieve a bidirectional
communication.

Real-world example

By implementing the Mediator design pattern, we are going to develop a modular


application, which will have a Mediator as a central communication point for all the
modules, eliminating the possibility to have a dependant relationship between
them.

Memento
Behavioral pattern

This design pattern allows us to record the state of an object on a specific moment
in order to return it to that state at any given time. Memento is useful when we
have many objects changing over time and, for some reason, we need to restore
them to a previous state.

The components included in the pattern are:


 Client: This component affects the Originator and records a new state into the Caretaker. In other words, it's the one making changes to the object and
recording its state.

 Originator: It is the component whose state is changing.

 Memento: It is the component storing the Originator's state on a specific moment.

 Caretaker: This is the component registering all the changes happening in the Originator. It allows us to travel to any previous state of the Originator.

1. The Client makes a change to the Originator.

2. The Originator creates a new Memento which represents its current state.

3. The Client stores the Memento into the Caretaker in order to change between different Originatorstates.

4. After some time, the Client sends a request to the Caretaker for a previous state of the Originator.

5. The Client uses the Memento sent by the Caretaker to restore the state of the Originator .

Real-world example

By implementing the Memento design pattern, we are going to develop a simple


but effective application for receiving information about an employee. Once the
information is stored, the application will allow us to go back or forward between
different versions of this information that were stored by the Memento pattern, as if
we were using an undo (Ctrl + Z) and redo features (Ctrl + Y).
Null Object
Behavioral pattern

The Null Object pattern was created due to the need of avoiding the appearance of
null values that can cause runtime errors. What this pattern basically proposes is
using instances for implementing the required interface but with a void body,
instead of returning a null value.

The components included in the pattern are:

 Client: Component interacting with the potentially null object.

 AbstractObject: Common interface between the real object and its null representation.

 ConcreteObject: Class representing a real object, which has a concrete implementation; it will be created only when the requested object exists.

 NullObject: Object which implements void methods. It will be created only when a requested object does not exist, and it’s going to be returned instead
of a null reference.
1. The client looks for a specific object.

2. ObjectLookup checks if the requested object exists.

3. If the requested object doesn't exist, an instance of NullObjectwill be returned.

4. On the other hand, if the requested object is located, an instance of ConcreteObjectwill be returned.

5. The client receives any of the two mentioned instances, however, it will never get a null reference if the object were not to be found.

Real-world example

By implementing the Null Object design pattern, we are going to develop an


employee search service, which will avoid sending null instances whenever an
employee is not found. If the requested employee is not found, a NullEmployee will
be returned, that is, the null representation of an employee.

State
Behavioral pattern

The State design pattern characterizes for changing its behavior depending on the
state of the application. To achieve this, it’s necessary to create a series of classes
for representing the different states an application can go through, that is, one
class for each state of the application.
The components included in the State design pattern are as follows:

 Context: It represents the component subject to changing states, it has its current state as one of its properties. Going back to the vending machine
example, this would represent the machine.

 AbstractState: Base class used for generating different states. This works better as an abstract class, instead of as an interface, because it allows us to
set behaviors by default and alter the operation on every state.

 ConcreteState: Each one of these components represent a state the application could go through during its execution, which is why we’re going to have
a ConcreteState for each possible state. This class must inherit from AbstractState.

1. A state by default is set in the Context, this is StateA.

2. A request operation is executed in the Context, delegating the execution to the current state (StateA).

3. The Context changes from StateA to StateB.

4. Again, a request operation is executed in the Context delegating the execution to the current state (StateB).

5. The execution of StateB results in a change to StateC.

6. A new request operation is executed in the Context delegating the execution to the current state (StateC).

Real-world example

By implementing the State design pattern, we are going to create our own server,
which will be control through a series of states. These states will tell the server
how to behave under different events, because the same event can provide
different results depending on the current state of the server.
Visitor
Behavioral pattern

The Visitor design pattern is used for separating the logic and operations
performed over a complex structure. On occasions, we can find data structures
requiring various operations to be performed and needing new ones to be created
as the application grows.

As the application grows, so does the number of operations included in the


structure, making it very difficult to manage. This where the Visitor design patterns
enters, it proposes the separation of these operations into independent classes
called Visitors, created with a common interface and a basic structure for adding
operations without having to make modifications to it.

1. The client creates the structure (Element).

2. The client creates the instance of the Visitor to be used in the structure.

3. The client executes the accept method of the structure and sends the Visitor.

4. The Element tells the Visitor which method must be used for processing it. The Visitor must have a method for each class type included in the structure.

5. The Visitor analyzes the Element using its visitElement method and repeats the accept method execution process over the Element's children. Again, the
Visitor must have a method for each class type included in the structure.

6. The ConcreteElementA tells the Visitor visitor which method must be used for processing it, that is visitElementA.

7. The Visitor proceeds with the rest of the children of the Element and executes the accept method on ConcreteElementB.

8. The ConcrteElementB tells the Visitor which method must be used for processing it, that is visitElementB.

9. Lastly, the Visitor ends the operation performed over the structure after having traversed all the objects, providing results available for the client by
request using the getResults method (this is optional, because some operations won't produce any results).

Real-world example

By implementing the Visitor design pattern, we are going to review how a plan to
build a Microsoft Project type project is analyzed and evaluated to get the
information we require. To that end, we will develop a work plan which includes
activities and personnel forming a hierarchical structure similar to a tree.

You might also like