Você está na página 1de 144

What are Software Design Principles?

Software design principles represent a set of guidelines that helps us to avoid having a bad
design. The design principles are associated to Robert Martin who gathered them in "Agile
Software Development: Principles, Patterns, and Practices". According to Robert Martin
there are 3 important characteristics of a bad design that should be avoided:
Rigidity - It is hard to change because every change affects too many other parts of the
system.
Fragility - When you make a change, unexpected parts of the system break.
Immobility - It is hard to reuse in another application because it cannot be disentangled
from the current application.
Open Close Principle
Software entities like classes, modules and functions should be open for
extension but closed for modifications.
OPC is a generic principle. You can consider it when writing your classes to make sure that
when you need to extend their behavior you dont have to change the class but to extend it.
The same principle can be applied for modules, packages, libraries. If you have a library
containing a set of classes there are many reasons for which youll prefer to extend it
without changing the code that was already written (backward compatibility, regression
testing, ). This is why we have to make sure our modules follow Open Closed Principle.
When referring to the classes Open Close Principle can be ensured by use of Abstract
Classes and concrete classes for implementing their behavior. This will enforce having
Concrete Classes extending Abstract Classes instead of changing them. Some particular
cases of this are Template Pattern and Strategy Pattern.
Dependency Inversion Principle
High-level modules should not depend on low-level modules. Both should depend on
abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
Dependency Inversion Principle states that we should decouple high level modules from low
level modules, introducing an abstraction layer between the high level classes and low level
classes. Furthermore it inverts the dependency: instead of writing our abstractions based on
details, we should write the details based on abstractions.
Dependency Inversion or Inversion of Control are better know terms referring to the way in
which the dependencies are realized. In the classical way when a software module (class,
framework, ) need some other module, it initializes and holds a direct reference to it. This
will make the 2 modules tight coupled. In order to decouple them the first module will
provide a hook(a property, parameter, ) and an external module controlling the
dependencies will inject the reference to the second one.
By applying the Dependency Inversion the modules can be easily changed by other modules
just changing the dependency module. Factories and Abstract Factories can be used as
dependency frameworks, but there are specialized frameworks for that, known as Inversion
of Control Container.
Interface Segregation Principle
Clients should not be forced to depend upon interfaces that they don't use.
This principle teaches us to take care how we write our interfaces. When we write our
interfaces we should take care to add only methods that should be there. If we add methods
that should not be there the classes implementing the interface will have to implement
those methods as well. For example if we create an interface called Worker and add a
method lunch break, all the workers will have to implement it. What if the worker is a
robot?
As a conclusion Interfaces containing methods that are not specific to it are called polluted
or fat interfaces. We should avoid them.
Single Responsibility Principle
A class should have only one reason to change.
In this context a responsibility is considered to be one reason to change. This principle
states that if we have 2 reasons to change for a class, we have to split the functionality in
two classes. Each class will handle only one responsibility and on future if we need to make
one change we are going to make it in the class which handles it. When we need to make a
change in a class having more responsibilities the change might affect the other
functionality of the classes.
Single Responsibility Principle was introduced Tom DeMarco in his book Structured Analysis
and Systems Specification, 1979. Robert Martin reinterpreted the concept and defined the
responsibility as a reason to change.
Liskov's Substitution Principle
Derived types must be completely substitutable for their base types.
This principle is just an extension of the Open Close Principle in terms of behavior meaning
that we must make sure that new derived classes are extending the base classes without
changing their behavior. The new derived classes should be able to replace the base classes
without any change in the code.
Liskov's Substitution Principle was introduced by Barbara Liskov in a 1987 Conference on
Object Oriented Programming Systems Languages and Applications, in Data abstraction and
hierarchy
Open Close Principle

Motivation
A clever application design and the code writing part should take care of the frequent
changes that are done during the development and the maintaining phase of an application.
Usually, many changes are involved when a new functionality is added to an application.
Those changes in the existing code should be minimized, since it's assumed that the
existing code is already unit tested and changes in already written code might affect the
existing functionality in an unwanted manner.
The Open Close Principle states that the design and writing of the code should be done in
a way that new functionality should be added with minimum changes in the existing code.
The design should be done in a way to allow the adding of new functionality as new classes,
keeping as much as possible existing code unchanged.
Intent
Software entities like classes, modules and functions should be open for
extension but closed for modifications.
Example
Bellow is an example which violates the Open Close Principle. It implements a graphic editor
which handles the drawing of different shapes. It's obviously that it does not follow the
Open Close Principle since the GraphicEditor class has to be modified for every new shape
class that has to be added. There are several disadvantages:
for each new shape added the unit testing of the GraphicEditor should be redone.
when a new type of shape is added the time for adding it will be high since the developer
who add it should understand the logic of the GraphicEditor.
adding a new shape might affect the existing functionality in an undesired way, even if the
new shape works perfectly
In order to have more dramatic effect, just imagine that the Graphic Editor is a big class,
with a lot of functionality inside, written and changed by many developers, while the shape
might be a class implemented only by one developer. In this case it would be great
improvement to allow the adding of a new shape without changing the GraphicEditor class.


// Open-Close Principle - Bad example
class GraphicEditor {

public void drawShape(Shape s) {
if (s.m_type==1)
drawRectangle(s);
else if (s.m_type==2)
drawCircle(s);
}
public void drawCircle(Circle r) {....}
public void drawRectangle(Rectangle r) {....}
}

class Shape {
int m_type;
}

class Rectangle extends Shape {
Rectangle() {
super.m_type=1;
}
}

class Circle extends Shape {
Circle() {
super.m_type=2;
}
}

Below is an example which supports the Open Close Principle. In the new design we use
abstract draw() method in GraphicEditor for drawing objects, while moving the
implementation in the concrete shape objects. Using the Open Close Principle the problems
from the previous design are avoided, because GraphicEditor is not changed when a new
shape class is added:
no unit testing required.
no need to understand the sourcecode from GraphicEditor.
Since the drawing code is moved to the concrete shape classes, it's a reduced risk to affect
old functionality when new functionality is added.


//Open-ClosePrinciple - Good example
class GraphicEditor {
public void drawShape(Shape s) {
s.draw();
}
}

class Shape {
abstract void draw();
}

class Rectangle extends Shape {
public void draw() {
// draw the rectangle
}
}

Conclusion
Like every principle OCP is only a principle. Making a flexible design involves additional time
and effort spent for it and it introduce new level of abstraction increasing the complexity of
the code. So this principle should be applied in those areas which are most likely to be
changed.
There are many design patterns that help us to extend code without changing it. For
instance the Decorator pattern helps us to follow Open Close principle. Also the Factory
Method or the Observer pattern might be used to design an application easy to change with
minimum changes in the existing code.
Dependency Inversion Principle
Motivation
When we design software applications we can consider the low level classes the classes
which implement basic and primary operations(disk access, network protocols,...) and high
level classes the classes which encapsulate complex logic(business flows, ...). The last ones
rely on the low level classes. A natural way of implementing such structures would be to
write low level classes and once we have them to write the complex high level classes.
Since high level classes are defined in terms of others this seems the logical way to do it.
But this is not a flexible design. What happens if we need to replace a low level class?
Let's take the classical example of a copy module which reads characters from the keyboard
and writes them to the printer device. The high level class containing the logic is the Copy
class. The low level classes are KeyboardReader and PrinterWriter.
In a bad design the high level class uses directly and depends heavily on the low level
classes. In such a case if we want to change the design to direct the output to a new
FileWriter class we have to make changes in the Copy class. (Let's assume that it is a very
complex class, with a lot of logic and really hard to test).
In order to avoid such problems we can introduce an abstraction layer between high level
classes and low level classes. Since the high level modules contain the complex logic they
should not depend on the low level modules so the new abstraction layer should not be
created based on low level modules. Low level modules are to be created based on the
abstraction layer.
According to this principle the way of designing a class structure is to start from high level
modules to the low level modules:
High Level Classes --> Abstraction Layer --> Low Level Classes
Intent
High-level modules should not depend on low-level modules. Both should depend on
abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
Example
Below is an example which violates the Dependency Inversion Principle. We have the
manager class which is a high level class, and the low level class called Worker. We need to
add a new module to our application to model the changes in the company structure
determined by the employment of new specialized workers. We created a new class
SuperWorker for this.
Let's assume the Manager class is quite complex, containing very complex logic. And now
we have to change it in order to introduce the new SuperWorker. Let's see the
disadvantages:
We have to change the Manager class (remember it is a complex one and this will involve
time and effort to make the changes).
Some of the current functionality from the manager class might be affected.
The unit testing should be redone.
All those problems could take a lot of time to be solved and they might induce new errors in
the old functionality. The situation would be different if the application had been designed
following the Dependency Inversion Principle. It means we design the manager class, an
IWorker interface and the Worker class implementing the IWorker interface. When we need
to add the SuperWorker class all we have to do is implement the IWorker interface for it. No
additional changes in the existing classes.
// Dependency Inversion Principle - Bad example

class Worker {

public void work() {

// ....working

}

}

class Manager {

Worker worker;



public void setWorker(Worker w) {
worker = w;
}

public void manage() {
worker.work();
}
}

class SuperWorker {
public void work() {
//.... working much more
}
}


Below is the code which supports the Dependency Inversion Principle. In this new design a
new abstraction layer is added through the IWorker Interface. Now the problems from the
above code are solved (considering there is no change in the high level logic):
Manager class doesn't require changes when adding SuperWorkers.
Minimized risk to affect old functionality present in Manager class since we don't change it.
No need to redo the unit testing for Manager class.
// Dependency Inversion Principle - Good example
interface IWorker {
public void work();
}

class Worker implements IWorker{
public void work() {
// ....working
}
}

class SuperWorker implements IWorker{
public void work() {
//.... working much more
}
}

class Manager {
IWorker worker;

public void setWorker(IWorker w) {
worker = w;
}

public void manage() {
worker.work();
}
}


Conclusion
When this principle is applied it means the high level classes are not working directly with
low level classes, they are using interfaces as an abstract layer. In this case instantiation of
new low level objects inside the high level classes (if necessary) cannot be done using the
operator new. Instead, some of the Creational design patterns can be used, such as Factory
Method, Abstract Factory, Prototype.
The Template Design Pattern is an example where the DIP principle is applied.
Of course, using this principle implies an increased effort, will result in more classes and
interfaces to maintain, in a few words in more complex code, but more flexible. This
principle should not be applied blindly for every class or every module. If we have a class
functionality that is more likely to remain unchanged in the future there is no need to apply
this principle.

Interface Segregation Principle (ISP)


Motivation
When we design an application we should take care how we are going to make abstract a
module which contains several submodules. Considering the module implemented by a
class, we can have an abstraction of the system done in an interface. But if we want to
extend our application adding another module that contains only some of the submodules of
the original system, we are forced to implement the full interface and to write some dummy
methods. Such an interface is named fat interface or polluted interface. Having an interface
pollution is not a good solution and might induce inappropriate behavior in the system.
The Interface Segregation Principle states that clients should not be forced to
implement interfaces they don't use. Instead of one fat interface many small interfaces are
preferred based on groups of methods, each one serving one submodule.
Intent
Clients should not be forced to depend upon interfaces that they don't use.
Example
Below is an example which violates the Interface Segregation Principle. We have a Manager
class which represent the person which manages the workers. And we have 2 types of
workers some average and some very efficient workers. Both types of workers works and
they need a daily launch break to eat. But now some robots came in the company they work
as well , but they don't eat so they don't need a launch break. One on side the new Robot
class need to implement the IWorker interface because robots works. On the other side, the
don't have to implement it because they don't eat.
This is why in this case the IWorker is considered a polluted interface.
If we keep the present design, the new Robot class is forced to implement the eat method.
We can write a dummy class which does nothing(let's say a launch break of 1 second daily),
and can have undesired effects in the application(For example the reports seen by
managers will report more lunches taken than the number of people).
According to the Interface Segregation Principle, a flexible design will not have polluted
interfaces. In our case the IWorker interface should be split in 2 different interfaces.
// interface segregation principle - bad example
interface IWorker {
public void work();
public void eat();
}

class Worker implements IWorker{
public void work() {
// ....working
}
public void eat() {
// ...... eating in launch break
}
}

class SuperWorker implements IWorker{
public void work() {
//.... working much more
}

public void eat() {
//.... eating in launch break
}
}

class Manager {
IWorker worker;

public void setWorker(IWorker w) {
worker=w;
}

public void manage() {
worker.work();
}
}

Following it's the code supporting the Interface Segregation Principle. By splitting the
IWorker interface in 2 different interfaces the new Robot class is no longer forced to
implement the eat method. Also if we need another functionality for the robot like
recharging we create another interface IRechargeble with a method recharge.
// interface segregation principle - good example
interface IWorker extends Feedable, Workable {
}

interface IWorkable {
public void work();
}

interface IFeedable{
public void eat();
}

class Worker implements IWorkable, IFeedable{
public void work() {
// ....working
}

public void eat() {
//.... eating in launch break
}
}

class Robot implements IWorkable{
public void work() {
// ....working
}
}

class SuperWorker implements IWorkable, IFeedable{
public void work() {
//.... working much more
}

public void eat() {
//.... eating in launch break
}
}

class Manager {
Workable worker;

public void setWorker(Workable w) {
worker=w;
}

public void manage() {
worker.work();
}
}
Conclusion
If the design is already done fat interfaces can be segregated using the Adapter pattern.
Like every principle Interface Segregation Principle is one principle which require additional
time and effort spent to apply it during the design time and increase the complexity of code.
But it produce a flexible design. If we are going to apply it more than is necessary it will
result a code containing a lot of interfaces with single methods, so applying should be done
based on experience and common sense in identifying the areas where extension of code
are more likely to happens in the future.
Single Responsibility Principle

Motivation
In this context a responsibility is considered to be one reason to change. This principle
states that if we have 2 reasons to change for a class, we have to split the functionality in
two classes. Each class will handle only one responsibility and on future if we need to make
one change we are going to make it in the class which handle it. When we need to make a
change in a class having more responsibilities the change might affect the other
functionality of the classes.
The Single Responsibility Principle is a simple and intuitive principle, but in practice it is
sometimes hard to get it right.
Intent
A class should have only one reason to change.
Example
Let's assume we need an object to keep an email message. We are going to use the IEmail
interface from the below sample. At the first sight everything looks just fine. At a closer look
we can see that our IEmail interface and Email class have 2 responsibilities (reasons to
change). One would be the use of the class in some email protocols such as pop3 or imap. If
other protocols must be supported the objects should be serialized in another manner and
code should be added to support new protocols. Another one would be for the Content field.
Even if content is a string maybe we want in the future to support HTML or other formats.
If we keep only one class, each change for a responsibility might affect the other one:
Adding a new protocol will create the need to add code for parsing and serializing the
content for each type of field.
Adding a new content type (like html) make us to add code for each protocol implemented.
// single responsibility principle - bad example

interface IEmail {
public void setSender(String sender);
public void setReceiver(String receiver);
public void setContent(String content);
}

class Email implements IEmail {
public void setSender(String sender) {// set sender; }
public void setReceiver(String receiver) {// set receiver; }
public void setContent(String content) {// set content; }
}


We can create a new interface and class called IContent and Content to split the
responsibilities. Having only one responsibility for each class give us a more flexible design:
adding a new protocol causes changes only in the Email class.
adding a new type of content supported causes changes only in Content class.

// single responsibility principle - good example
interface IEmail {
public void setSender(String sender);
public void setReceiver(String receiver);
public void setContent(IContent content);
}

interface Content {
public String getAsString(); // used for serialization
}

class Email implements IEmail {
public void setSender(String sender) {// set sender; }
public void setReceiver(String receiver) {// set receiver; }
public void setContent(IContent content) {// set content; }
}


Conclusion
The Single Responsibility Principle represents a good way of identifying classes during the
design phase of an application and it reminds you to think of all the ways a class can evolve.
A good separation of responsibilities is done only when the full picture of how the
application should work is well understand.
Liskov's Substitution Principle(LSP)


Motivation
All the time we design a program module and we create some class hierarchies. Then we
extend some classes creating some derived classes.
We must make sure that the new derived classes just extend without replacing the
functionality of old classes. Otherwise the new classes can produce undesired effects when
they are used in existing program modules.
Likov's Substitution Principle states that if a program module is using a Base class, then the
reference to the Base class can be replaced with a Derived class without affecting the
functionality of the program module.
Intent
Derived types must be completely substitutable for their base types.
Example
Below is the classic example for which the Likov's Substitution Principle is violated. In the
example 2 classes are used: Rectangle and Square. Let's assume that the Rectangle object
is used somewhere in the application. We extend the application and add the Square class.
The square class is returned by a factory pattern, based on some conditions and we don't
know the exact what type of object will be returned. But we know it's a Rectangle. We get
the rectangle object, set the width to 5 and height to 10 and get the area. For a rectangle
with width 5 and height 10 the area should be 50. Instead the result will be 100

// Violation of Likov's Substitution Principle
class Rectangle
{
protected int m_width;
protected int m_height;

public void setWidth(int width){
m_width = width;
}

public void setHeight(int height){
m_height = height;
}


public int getWidth(){
return m_width;
}

public int getHeight(){
return m_height;
}

public int getArea(){
return m_width * m_height;
}
}

class Square extends Rectangle
{
public void setWidth(int width){
m_width = width;
m_height = width;
}

public void setHeight(int height){
m_width = height;
m_height = height;
}

}

class LspTest
{
private static Rectangle getNewRectangle()
{
// it can be an object returned by some factory ...
return new Square();
}

public static void main (String args[])
{
Rectangle r = LspTest.getNewRectangle();

r.setWidth(5);
r.setHeight(10);
// user knows that r it's a rectangle.
// It assumes that he's able to set the width and height as
for the base class

System.out.println(r.getArea());
// now he's surprised to see that the area is 100 instead of
50.
}
}
Conclusion
This principle is just an extension of the Open Close Principle and it means that we must
make sure that new derived classes are extending the base classes without changing their
behavior.

Singleton Pattern
Motivation
Sometimes it's important to have only one instance for a class. For example, in a system
there should be only one window manager (or only a file system or only a print spooler).
Usually singletons are used for centralized management of internal or external resources
and they provide a global point of access to themselves.
The singleton pattern is one of the simplest design patterns: it involves only one class which
is responsible to instantiate itself, to make sure it creates not more than one instance; in
the same time it provides a global point of access to that instance. In this case the same
instance can be used from everywhere, being impossible to invoke directly the constructor
each time.
Intent
Ensure that only one instance of a class is created.
Provide a global point of access to the object.
Implementation
The implementation involves a static member in the "Singleton" class, a private constructor
and a static public method that returns a reference to the static member.

The Singleton Pattern defines a getInstance operation which exposes the unique instance
which is accessed by the clients. getInstance() is is responsible for creating its class unique
instance in case it is not created yet and to return that instance.
class Singleton
{
private static Singleton instance;
private Singleton()
{
...
}

public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();

return instance;
}
...
public void doSomething()
{
...
}
}
You can notice in the above code that getInstance method ensures that only one instance of
the class is created. The constructor should not be accessible from the outside of the class
to ensure the only way of instantiating the class would be only through the getInstance
method.
The getInstance method is used also to provide a global point of access to the object and it
can be used in the following manner:
Singleton.getInstance().doSomething();

Applicability & Examples
According to the definition the singleton pattern should be used when there must be exactly
one instance of a class, and when it must be accessible to clients from a global access point.
Here are some real situations where the singleton is used:

Example 1 - Logger Classes
The Singleton pattern is used in the design of logger classes. This classes are ussualy
implemented as a singletons, and provides a global logging access point in all the
application components without being necessary to create an object each time a logging
operations is performed.
Example 2 - Configuration Classes
The Singleton pattern is used to design the classes which provides the configuration settings
for an application. By implementing configuration classes as Singleton not only that we
provide a global access point, but we also keep the instance we use as a cache object.
When the class is instantiated( or when a value is read ) the singleton will keep the values
in its internal structure. If the values are read from the database or from files this avoids
the reloading the values each time the configuration parameters are used.

Example 3 - Accesing resources in shared mode
It can be used in the design of an application that needs to work with the serial port. Let's
say that there are many classes in the application, working in an multi-threading
environment, which needs to operate actions on the serial port. In this case a singleton with
synchronized methods could be used to be used to manage all the operations on the serial
port.
Example 4 - Factories implemented as Singletons
Let's assume that we design an application with a factory to generate new objects(Acount,
Customer, Site, Address objects) with their ids, in an multithreading environment. If the
factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids
for 2 different objects. If we implement the Factory as a singleton we avoid this problem.
Combining Abstract Factory or Factory Method and Singleton design patterns is a common
practice.
Specific problems and implementation
Thread-safe implementation for multi-threading use.
A robust singleton implementation should work in any conditions. This is why we need to
ensure it works when multiple threads uses it. As seen in the previous examples singletons
can be used specifically in multi-threaded application to make sure the reads/writes are
synchronized.
Lazy instantiation using double locking mechanism.
The standard implementation shown in the above code is a thread safe implementation, but
it's not the best thread-safe implementation beacuse synchronization is very expensive
when we are talking about the performance. We can see that the synchronized method
getInstance does not need to be checked for syncronization after the object is initialized. If
we see that the singleton object is already created we just have to return it without using
any syncronized block. This optimization consist in checking in an unsynchronized block if
the object is null and if not to check again and create it in an syncronized block. This is
called double locking mechanism.
In this case case the singleton instance is created when the getInstance() method is called
for the first time. This is called lazy instantiation and it ensures that the singleton instance is
created only when it is needed.
//Lazy instantiation using double locking mechanism.
class Singleton
{
private static Singleton instance;

private Singleton()
{
System.out.println("Singleton(): Initializing Instance");
}

public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class)
{
if (instance == null)
{
System.out.println("getInstance(): First
time getInstance was invoked!");
instance = new Singleton();
}
}
}

return instance;
}

public void doSomething()
{
System.out.println("doSomething(): Singleton does
something!");
}
}
A detialed discussion(double locking mechanism) can be found on http://www-
128.ibm.com/developerworks/java/library/j-dcl.html?loc=j
Early instantiation using implementation with static field
In the following implementattion the singleton object is instantiated when the class is
loaded and not when it is first used, due to the fact that the instance member is declared
static. This is why in we don't need to synchronize any portion of the code in this case. The
class is loaded once this guarantee the uniquity of the object.
Singleton - A simple example (java)
//Early instantiation using implementation with static field.
class Singleton
{
private static Singleton instance = new Singleton();

private Singleton()
{
System.out.println("Singleton(): Initializing Instance");
}

public static Singleton getInstance()
{
return instance;
}

public void doSomething()
{
System.out.println("doSomething(): Singleton does something!");
}
}


Protected constructor
It is possible to use a protected constructor to in order to permit the subclassing of the
singeton. This techique has 2 drawbacks that makes singleton inheritance impractical:
First of all, if the constructor is protected, it means that the class can be instantiated by
calling the constructor from another class in the same package. A possible solution to avoid
it is to create a separate package for the singleton.
Second of all, in order to use the derived class all the getInstance calls should be changed in
the existing code from Singleton.getInstance() to NewSingleton.getInstance().
Multiple singleton instances if classes loaded by different classloaders access a singleton.
If a class(same name, same package) is loaded by 2 diferent classloaders they represents 2
different clasess in memory.
Serialization
If the Singleton class implements the java.io.Serializable interface, when a singleton is
serialized and then deserialized more than once, there will be multiple instances of
Singleton created. In order to avoid this the readResolve method should be implemented.
See Serializable () and readResolve Method () in javadocs.
public class Singleton implements Serializable {
...

// This method is called immediately after an object of this
class is deserialized.
// This method returns the singleton instance.
protected Object readResolve() {
return getInstance();
}
}


Abstract Factory and Factory Methods implemented as singletons.
There are certain situations when the a factory should be unique. Having 2 factories might
have undesired effects when objects are created. To ensure that a factory is unique it
should be implemented as a singleton. By doing so we also avoid to instantiate the class
before using it.
Hot Spot:
Multithreading - A special care should be taken when singleton has to be used in a
multithreading application.
Serialization - When Singletons are implementing Serializable interface they have to
implement readResolve method in order to avoid having 2 different objects.
Classloaders - If the Singleton class is loaded by 2 different class loaders we'll have 2
different classes, one for each class loader.
Global Access Point represented by the class name - The singleton instance is
obtained using the class name. At the first view this is an easy way to access it, but it is not
very flexible. If we need to replace the Sigleton class, all the references in the code should
be changed accordinglly.

Factory Pattern
Motivation
The Factory Design Pattern is probably the most used design pattern in modern
programming languages like Java and C#. It comes in different variants and
implementations. If you are searching for it, most likely, you'll find references about the
GoF patterns: Factory Method and Abstract Factory.
In this article we'll describe a flavor of factory pattern commonly used nowdays. You can
also check the original Factory Method pattern which is very similar.
Intent
creates objects without exposing the instantiation logic to the client.
refers to the newly created object through a common interface
Implementation


The implementation is really simple
The client needs a product, but instead of creating it directly using the new operator, it asks
the factory object for a new product, providing the information about the type of object it
needs.
The factory instantiates a new concrete product and then returns to the client the newly
created product(casted to abstract product class).
The client uses the products as abstract products without being aware about their concrete
implementation.

Applicability & Examples
Probably the factory pattern is one of the most used patterns.
For example a graphical application works with shapes. In our implementation the drawing
framework is the client and the shapes are the products. All the shapes are derived from an
abstract shape class (or interface). The Shape class defines the draw and move operations
which must be implemented by the concrete shapes. Let's assume a command is selected
from the menu to create a new Circle. The framework receives the shape type as a string
parameter, it asks the factory to create a new shape sending the parameter received from
menu. The factory creates a new circle and returns it to the framework, casted to an
abstract shape. Then the framework uses the object as casted to the abstract class without
being aware of the concrete object type.
The advantage is obvious: New shapes can be added without changing a single line of code
in the framework(the client code that uses the shapes from the factory). As it is shown in
the next sections, there are certain factory implementations that allow adding new products
without even modifying the factory class.
Specific problems and implementation
Procedural Solution - switch/case noob instantiation.

Those are also known as parameterized Factories. The generating method can be written so
that it can generate more types of Product objects, using a condition (entered as a method
parameter or read from some global configuration parameters - see abstract factory
pattern) to identify the type of the object that should be created, as below:
public class ProductFactory{
public Product createProduct(String ProductID){
if (id==ID1)
return new OneProduct();
if (id==ID2) return
return new AnotherProduct();
... // so on for the other Ids

return null; //if the id doesn't have any of the expected values
}
...
}
This implementation is the most simple and intuitive (Let's call it noob implementation). The
problem here is that once we add a new concrete product call we should modify the Factory
class. It is not very flexible and it violates open close principle. Of course we can subclass
the factory class, but let's not forget that the factory class is usually used as a singleton.
Subclassing it means replacing all the factory class references everywhere through the
code.
Class Registration - using reflection
If you can use reflection, for example in Java or .NET languages, you can register new
product classes to the factory without even changing the factory itself. For creating objects
inside the factory class without knowing the object type we keep a map between the
productID and the class type of the product. In this case when a new product is added to
the application it has to be registered to the factory. This operation doesn't require any
change in the factory class code.
class ProductFactory
{
private HashMap m_RegisteredProducts = new HashMap();

public void registerProduct (String productID, Class productClass)
{
m_RegisteredProducts.put(productID, productClass);
}

public Product createProduct(String productID)
{
Class productClass =
(Class)m_RegisteredProducts.get(productID);
Constructor productConstructor =
cClass.getDeclaredConstructor(new Class[] { String.class });
return (Product)productConstructor.newInstance(new Object[] {
});
}
}
We can put the registration code anywhere in our code, but a convenient place is inside the
product class in a static constructor. Look at the example below:
1. Registration done outside of product classes:
public static void main(String args[]){
Factory.instance().registerProduct("ID1", OneProduct.class);
}
2. Registration done inside the product classes:
class OneProduct extends Product
{
static {
Factory.instance().registerProduct("ID1",OneProduct.class);
}
...
}
We have to make sure that the concrete product classes are loaded before they are required
by the factory for registration(if they are not loaded they will not be registered in the factory
and createProduct will return null). To ensure it we are going to use the Class.forName
method right in the static section of the main class. This section is executed right after the
main class is loaded. Class.forName is supposed to return a Class instance of the indicated
class. If the class is not loaded by the compiler yet, it will be loaded when the
Class.forName is invoked. Consequently the static block in each class will be executed when
each class is loaded:
class Main
{
static
{
try
{
Class.forName("OneProduct");
Class.forName("AnotherProduct");
}
catch (ClassNotFoundException any)
{
any.printStackTrace();
}
}
public static void main(String args[]) throws
PhoneCallNotRegisteredException
{
...
}
}
This reflection implementation has its own drawbacks. The main one is performance. When
the reflection is used the performance on code involving reflection can decrease even to
10% of the poerfomance of a non reflection code. Another issue is that not all the
programming languages provide reflection mechanism.

Class Registration - avoiding reflection
As we saw in the previous paragraph the factory object uses internally a HashMap to keep
the mapping between parameters (in our case Strings) and concrete products class. The
registration is made from outside of the factory and because the objects are created using
reflection the factory is not aware of the objects types.
We don't want to use reflection but in the same time we want to have a reduced coupling
between the factory and concrete products. Since the factory should be unaware of products
we have to move the creation of objects outside of the factory to an object aware of the
concrete products classes. That would be the concrete class itself.
We add a new abstract method in the product abstract class. Each concrete class will
implement this method to create a new object of the same type as itself. We also have to
change the registration method such that we'll register concrete product objects instead of
Class objects.
abstract class Product
{
public abstract Product createProduct();
...
}

class OneProduct extends Product
{
...
static
{
ProductFactory.instance().registerProduct("ID1", new
OneProduct());
}
public OneProduct createProduct()
{
return new OneProduct();
}
...
}

class ProductFactory
{
public void registerProduct(String productID, Product p) {
m_RegisteredProducts.put(productID, p);
}

public Product createProduct(String productID){
((Product)m_RegisteredProducts.get(productID)).createProduct();
}
}

A more advanced solution - Factory design pattern with abstractions(Factory Method)

This implementation represents an alternative for the class registration implementation.
Let's assume we need to add a new product to the application. For the procedural switch-
case implementation we need to change the Factory class, while in the class registration
implementation all we need is to register the class to the factory without actually modifying
the factory class. For sure this is a flexible solution.
The procedural implementation is the classical bad example for the Open-Close Principle. As
we can see there the most intuitive solution to avoid modifying the Factory class is to
extend it.
This is the classic implementation of the factory method pattern. There are some drawbacks
over the class registration implementation and not so many advantages:
+ The derived factory method can be changed to perform additional operations when the
objects are created (maybe some initialization based on some global parameters ...).
- The factory can not be used as a singleton.
- Each factory has to be initialized before using it.
- More difficult to implement.
- If a new object has to be added a new factory has to be created.
Anyway, this classic implementation has the advantage that it will help us understanding
the Abstract Factory design pattern.
Conclusion:
When you design an application just think if you really need it a factory to create objects.
Maybe using it will bring unnecessary complexity in your application. If you have many
objects of the same base type and you manipulate them mostly casted to abstract types,
then you need a factory. If you're code should have a lot of code like the following, you
should reconsider it:
(if (ConcreteProduct)genericProduct typeof )
((ConcreteProduct)genericProduct).doSomeConcreteOperation().
If you decided to go for a factory, I would recommend using one of class registration
implementations(with or without reflection) and to avoid the Factory Method (Factory design
pattern with abstractions). Please note the procedural switch-case (noob) implementation is
the simplest, violates the OCP principle is used only to explain the theory. The only wise
way to use it is for temporary modules until it is replaced with a real factory.

Factory Method Pattern
Motivation
Also known as Virtual Constructor, the Factory Method is related to the idea on which
libraries work: a library uses abstract classes for defining and maintaining relations between
objects. One type of responsibility is creating such objects. The library knows when an
object needs to be created, but not what kind of object it should create, this being specific
to the application using the library.
The Factory method works just the same way: it defines an interface for creating an object,
but leaves the choice of its type to the subclasses, creation being deferred at run-time. A
simple real life example of the Factory Method is the hotel. When staying in a hotel you first
have to check in. The person working at the front desk will give you a key to your room
after you've paid for the room you want and this way he can be looked at as a room
factory. While staying at the hotel, you might need to make a phone call, so you call the
front desk and the person there will connect you with the number you need, becoming a
phone-call factory, because he controls the access to calls, too.
Intent
Defines an interface for creating objects, but let subclasses to decide which class to
instantiate
Refers to the newly created object through a common interface

Implementation
The pattern basically works as shown below, in the UML diagram:


The participants classes in this pattern are:
Product defines the interface for objects the factory method creates.
ConcreteProduct implements the Product interface.
Creator(also refered as Factory because it creates the Product objects) declares the
method FactoryMethod, which returns a Product object. May call the generating method
for creating Product objects
ConcreteCreator overrides the generating method for creating ConcreteProduct objects
All concrete products are subclasses of the Product class, so all of them have the same basic
implementation, at some extent. The Creator class specifies all standard and generic
behavior of the products and when a new product is needed, it sends the creation details
that are supplied by the client to the ConcreteCreator. Having this diagram in mind, it is
easy for us now to produce the code related to it. Here is how the implementation of the
classic Factory method should look:
public interface Product { }

public abstract class Creator
{
public void anOperation()
{
Product product = factoryMethod();
}

protected abstract Product factoryMethod();
}

public class ConcreteProduct implements Product { }

public class ConcreteCreator extends Creator
{
protected Product factoryMethod()
{
return new ConcreteProduct();
}
}

public class Client
{
public static void main( String arg[] )
{
Creator creator = new ConcreteCreator();
creator.anOperation();
}
}
Applicability & Examples
The need for implementing the Factory Method is very frequent. The cases are the ones
below:
when a class can't anticipate the type of the objects it is supposed to create
when a class wants its subclasses to be the ones to specific the type of a newly created
object

Example 1 - Documents Application.
Take into consideration a framework for desktop applications. Such applications are meant
to work with documents. A framework for desktop applications contains definitions for
operations such as opening, creating and saving a document. The basic classes are abstract
ones, named Application and Document, their clients having to create subclasses from them
in order to define their own applications. For generating a drawing application, for example,
they need to define the DrawingApplication and DrawingDocument classes. The Application
class has the task of managing the documents, taking action at the request of the client (for
example, when the user selects the open or save command form the menu).
Because the Document class that needs to be instantiated is specific to the application, the
Application class does not know it in advance, so it doesn't know what to instantiate, but it
does know when to instantiate it. The framework needs to instantiate a certain class, but it
only knows abstract classes that can't be instantiated.
The Factory Method design pattern solves the problem by putting all the information related
to the class that needs to be instantiated into an object and using them outside the
framework, as you can see below

In the Application class the CreateDocument method either has a default implementation or
it doesn't have any implementation at all, this operation being redefined in the
MyApplication subclass so that it creates a MyDocument object and returns a reference to it.
public Document CreateDocument(String type){
if (type.isEqual("html"))
return new HtmlDocument();
if (type.isEqual("proprietary"))
return new MyDocument();
if (type.isEqual("pdf"))
return new PdfDocument ();
}
Assuming that the Application class has a member called docs that represents a list of
documents being handled by the application, then the NewDocument method should look
like this:
public void NewDocument(String type){
Document doc=CreateDocument(type);
Docs.add(doc);
Doc.Open();
}
This method will be inherited by the MyApplication class and, so, through the
CreateDocument method, it will actually instantiate MyDocument objects. We will call the
CreateDocument method a Factory Method because it is responsible with 'making' an object.
Through this method, redefined in Application's subclasses, we can actually shape the
situation in which the Application class creates objects without knowing their type. From this
point of view the factory method is pattern which provides us a way to achieve the DIP
principle.


Specific problems and implementation
When implementing the Factory Method design pattern some issues may appear:
Definition of Creator class
If we apply the pattern to an already written code there may be problems with the way we
have the Creator class already defined. There are two cases:
Creator class is abstract and generating method does not have any implementation. In this
case the ConcreteCreator classes must define their own generation method and this
situation usually appears in the cases where the Creator class can't foresee what
ConcreteProduct it will instantiate.
Creator class is a concrete class, the generating method having a default implementation. If
this happens, the ConcreteCreator classes will use the generating method for flexibility
rather than for generation. The programmer will always be able to modify the class of the
objects that the Creator class implicitly creates, redefining the generation method.
Factory method is just a particular case of the factory design pattern. In the same time it is
the most known factory pattern, maybe because it was published in the GoF. In modern
programming languages the factory with registration is more used.
Drawbacks and Benefits
Here are the benefits and drawbacks of factory method pattern:
+ The main reason for which the factory pattern is used is that it introduces a separation
between the application and a family of classes (it introduces weak coupling instead of tight
coupling hiding concrete classes from the application). It provides a simple way of extending
the family of products with minor changes in application code.
+ It provides customization hooks. When the objects are created directly inside the class it's
hard to replace them by objects which extend their functionality. If a factory is used instead
to create a family of objects the customized objects can easily replace the original objects,
configuring the factory to create them.
- The factory has to be used for a family of objects. If the classes doesn't extend common
base class or interface they can not be used in a factory design template.
Hot Points:
The factory method is one of the most used and one of the more robust design patterns.
There are only few points which have to be considered when you implement a factory
method.
When you design an application just think if you really need it a factory to create objects.
Maybe using it will bring unnecessary complexity in your application. Anyway if you have
many object of the same base type and you manipulate them mostly as abstract objects,
then you need a factory. I you're code should have a lot of code like the following,
reconsider it.
if (genericProduct typeof ConcreteProduct)
((ConcreteProduct)genericProduct).doSomeConcreteOperation();


Abstract Factory
Motivation
Modularization is a big issue in today's programming. Programmers all over the world are
trying to avoid the idea of adding code to existing classes in order to make them support
encapsulating more general information. Take the case of a information manager which
manages phone number. Phone numbers have a particular rule on which they get generated
depending on areas and countries. If at some point the application should be changed in
order to support adding numbers form a new country, the code of the application would
have to be changed and it would become more and more complicated.
In order to prevent it, the Abstract Factory design pattern is used. Using this pattern a
framework is defined, which produces objects that follow a general pattern and at runtime
this factory is paired with any concrete factory to produce objects that follow the pattern of
a certain country. In other words, the Abstract Factory is a super-factory which creates
other factories (Factory of factories).
Intent
Abstract Factory offers the interface for creating a family of related objects, without
explicitly specifying their classes.
Implementation
The pattern basically works as shown below, in the UML diagram:

The classes that participate to the Abstract Factory pattern are:
AbstractFactory - declares a interface for operations that create abstract products.
ConcreteFactory - implements operations to create concrete products.
AbstractProduct - declares an interface for a type of product objects.
Product - defines a product to be created by the corresponding ConcreteFactory; it
implements the AbstractProduct interface.
Client - uses the interfaces declared by the AbstractFactory and AbstractProduct classes.
The AbstractFactory class is the one that determines the actual type of the concrete object
and creates it, but it returns an abstract pointer to the concrete object just created. This
determines the behavior of the client that asks the factory to create an object of a certain
abstract type and to return the abstract pointer to it, keeping the client from knowing
anything about the actual creation of the object.
The fact that the factory returns an abstract pointer to the created object means that the
client doesn't have knowledge of the object's type. This implies that there is no need for
including any class declarations relating to the concrete type, the client dealing at all times
with the abstract type. The objects of the concrete type, created by the factory, are
accessed by the client only through the abstract interface.
The second implication of this way of creating objects is that when the adding new concrete
types is needed, all we have to do is modify the client code and make it use a different
factory, which is far easier than instantiating a new type, which requires changing the code
wherever a new object is created.
The classic implementation for the Abstract Factory pattern is the following:
abstract class AbstractProductA{
public abstract void operationA1();
public abstract void operationA2();
}

class ProductA1 extends AbstractProductA{
ProductA1(String arg){
System.out.println("Hello "+arg);
} // Implement the code here
public void operationA1() { };
public void operationA2() { };
}

class ProductA2 extends AbstractProductA{
ProductA2(String arg){
System.out.println("Hello "+arg);
} // Implement the code here
public void operationA1() { };
public void operationA2() { };
}

abstract class AbstractProductB{
//public abstract void operationB1();
//public abstract void operationB2();
}

class ProductB1 extends AbstractProductB{
ProductB1(String arg){
System.out.println("Hello "+arg);
} // Implement the code here
}

class ProductB2 extends AbstractProductB{
ProductB2(String arg){
System.out.println("Hello "+arg);
} // Implement the code here
}

abstract class AbstractFactory{
abstract AbstractProductA createProductA();
abstract AbstractProductB createProductB();
}

class ConcreteFactory1 extends AbstractFactory{
AbstractProductA createProductA(){
return new ProductA1("ProductA1");
}
AbstractProductB createProductB(){
return new ProductB1("ProductB1");
}
}

class ConcreteFactory2 extends AbstractFactory{
AbstractProductA createProductA(){
return new ProductA2("ProductA2");
}
AbstractProductB createProductB(){
return new ProductB2("ProductB2");
}
}

//Factory creator - an indirect way of instantiating the factories
class FactoryMaker{
private static AbstractFactory pf=null;
static AbstractFactory getFactory(String choice){
if(choice.equals("a")){
pf=new ConcreteFactory1();
}else if(choice.equals("b")){
pf=new ConcreteFactory2();
} return pf;
}
}

// Client
public class Client{
public static void main(String args[]){
AbstractFactory pf=FactoryMaker.getFactory("a");
AbstractProductA product=pf.createProductA();
//more function calls on product
}
}

Applicability & Examples
We should use the Abstract Factory design pattern when:
the system needs to be independent from the way the products it works with are created.
the system is or should be configured to work with multiple families of products.
a family of products is designed to work only all together.
the creation of a library of products is needed, for which is relevant only the interface, not
the implementation, too.



Phone Number Example
The example at the beginning of the article can be extended to addresses, too. The
AbstractFactory class will contain methods for creating a new entry in the information
manager for a phone number and for an address, methods that produce the abstract
products Address and PhoneNumber, which belong to AbstractProduct classes. The
AbstractProduct classes will define methods that these products support: for the address get
and set methods for the street, city, region and postal code members and for the phone
number get and set methods for the number.
The ConcreteFactory and ConcreteProduct classes will implement the interfaces defined
above and will appear in our example in the form of the USAddressFactory class and the
USAddress and USPhoneNumber classes. For each new country that needs to be added to
the application, a new set of concrete-type classes will be added. This way we can have the
EnglandAddressFactory and the EnglandAddress and EnglandPhoneNumber that are files for
English address information.
Pizza Factory Example
Another example, this time more simple and easier to understand, is the one of a pizza
factory, which defines method names and returns types to make different kinds of pizza.
The abstract factory can be named AbstractPizzaFactory, RomeConcretePizzaFactory and
MilanConcretePizzaFactory being two extensions of the abstract class. The abstract factory
will define types of toppings for pizza, like pepperoni, sausage or anchovy, and the concrete
factories will implement only a set of the toppings, which are specific for the area and even
if one topping is implemented in both concrete factories, the resulting pizzas will be different
subclasses, each for the area it was implemented in.
Look & Feel Example
Look & Feel Abstract Factory is the most common example. For example, a GUI framework
should support several look and feel themes, such as Motif and Windows look. Each style
defines different looks and behaviors for each type of controls: Buttons and Edit Boxes. In
order to avoid the hardociding it for each type of control we define an abstract
class LookAndFeel. This calls will instantiate, depending on a configuration parameter in
the application one of the concrete
factories:WindowsLookAndFeel or MotifLookAndFeel. Each request for a new
object will be delegated to the instatiated concrete factory which will return the controls
with the specific flavor

Specific problems and implementation
The Abstract Factory pattern has both benefits and flaws. On one hand it isolates the
creation of objects from the client that needs them, giving the client only the possibility of
accessing them through an interface, which makes the manipulation easier. The exchanging
of product families is easier, as the class of a concrete factory appears in the code only
where it is instantiated. Also if the products of a family are meant to work together, the
Abstract Factory makes it easy to use the objects from only one family at a time. On the
other hand, adding new products to the existing factories is difficult, because the Abstract
Factory interface uses a fixed set of products that can be created. That is why adding a new
product would mean extending the factory interface, which involves changes in the
AbstractFactory class and all its subclasses. This section will discuss ways of implementing
the pattern in order to avoid the problems that may appear.
Factories as singletons
An application usually needs only one instance of the ConcreteFactory class per family
product. This means that it is best to implement it as a Singleton.



Creating the products
The AbstractFactory class only declares the interface for creating the products. It is the task
of the ConcreteProduct class to actually create the products. For each family the best idea is
applying the Factory Method design pattern. A concrete factory will specify its products by
overriding the factory method for each of them. Even if the implementation might seem
simple, using this idea will mean defining a new concrete factory subclass for each product
family, even if the classes are similar in most aspects.
For simplifying the code and increase the performance the Prototype design pattern can be
used instead of Factory Method, especially when there are many product families. In this
case the concrete factory is initiated with a prototypical instance of each product in the
family and when a new one is needed instead of creating it, the existing prototype is cloned.
This approach eliminates the need for a new concrete factory for each new family of
products.
Extending the factories
The operation of changing a factory in order for it to support the creation of new products is
not easy. What can be done to solve this problem is, instead of a CreateProduct method for
each product, to use a single Create method that takes a parameter that identifies the type
of product needed. This approach is more flexible, but less secure. The problem is that all
the objects returned by the Create method will have the same interface, that is the one
corresponding to the type returned by the Create method and the client will not always be
able to correctly detect to which class the instance actually belongs.
Hot Points:
AbstractFactory class declares only an interface for creating the products. The actual
creation is the task of the ConcreteProduct classes, where a good approach is applying the
Factory Method design pattern for each product of the family.
Extending factories can be done by using one Create method for all products and attaching
information about the type of product needed.

Builder Pattern
Motivation
The more complex an application is the complexity of classes and objects used increases.
Complex objects are made of parts produced by other objects that need special care when
being built. An application might need a mechanism for building complex objects that is
independent from the ones that make up the object. If this is the problem you are being
confronted with, you might want to try using the Builder (or Adaptive Builder) design
pattern.
This pattern allows a client object to construct a complex object by specifying only its type
and content, being shielded from the details related to the objects representation. This
way the construction process can be used to create different representations. The logic of
this process is isolated form the actual steps used in creating the complex object, so the
process can be used again to create a different object form the same set of simple objects
as the first one.

Intent
Defines an instance for creating an object but letting subclasses decide which class to
instantiate
Refers to the newly created object through a common interface

Implementation
The Builder design pattern uses the Factory Builder pattern to decide which concrete class
to initiate in order to build the desired type of object, as we will see below in the UML
diagram:


The participants classes in this pattern are:
The Builder class specifies an abstract interface for creating parts of a Product object.
The ConcreteBuilder constructs and puts together parts of the product by implementing
the Builder interface. It defines and keeps track of the representation it creates and
provides an interface for saving the product.
The Director class constructs the complex object using the Builder interface.
The Product represents the complex object that is being built.
The client, that may be either another object or the actual client that calls the main()
method of the application, initiates the Builder and Director class. The Builder represents
the complex object that needs to be built in terms of simpler objects and types. The
constructor in the Director class receives a Builder object as a parameter from the Client
and is responsible for calling the appropriate methods of the Builder class. In order to
provide the Client with an interface for all concrete Builders, the Builder class should be an
abstract one. This way you can add new types of complex objects by only defining the
structure and reusing the logic for the actual construction process. The Client is the only one
that needs to know about the new types, the Director needing to know which methods of
the Builder to call.
The following example discusses the case of a text converting application:

The Client needs to convert a document from RTF format to ASCII format. There for, it calls
the method createASCIIText that takes as a parameter the document that will be converted.
This method calls the concrete builder, ASCIIConverter, that extends the Builder,
TextConverter, and overrides its two methods for converting characters and paragraphs,
and also the Director, RTFReader, that parses the document and calls the builders
methods depending on the type of token encountered. The product, the ASCIIText, is built
step by step, by appending converted characters.
//Abstract Builder
class abstract class TextConverter{
abstract void convertCharacter(char c);
abstract void convertParagraph();
}

// Product
class ASCIIText{
public void append(char c){ //Implement the code here }
}

//Concrete Builder
class ASCIIConverter extends TextConverter{
ASCIIText asciiTextObj;//resulting product

/*converts a character to target representation and appends to the
resulting*/
object void convertCharacter(char c){
char asciiChar = new Character(c).charValue();
//gets the ascii character
asciiTextObj.append(asciiChar);
}
void convertParagraph(){}
ASCIIText getResult(){
return asciiTextObj;
}
}

//This class abstracts the document object
class Document{
static int value;
char token;
public char getNextToken(){
//Get the next token
return token;
}
}

//Director
class RTFReader{
private static final char EOF='0'; //Delimitor for End of File
final char CHAR='c';
final char PARA='p';
char t;
TextConverter builder;
RTFReader(TextConverter obj){
builder=obj;
}
void parseRTF(Document doc){
while ((t=doc.getNextToken())!= EOF){
switch (t){
case CHAR: builder.convertCharacter(t);
case PARA: builder.convertParagraph();
}
}
}
}

//Client
public class Client{
void createASCIIText(Document doc){
ASCIIConverter asciiBuilder = new ASCIIConverter();
RTFReader rtfReader = new RTFReader(asciiBuilder);
rtfReader.parseRTF(doc);
ASCIIText asciiText = asciiBuilder.getResult();
}
public static void main(String args[]){
Client client=new Client();
Document doc=new Document();
client.createASCIIText(doc);
system.out.println("This is an example of Builder Pattern");
}
}

Applicability & Examples
Builder Pattern is used when:
the creation algorithm of a complex object is independent from the parts that actually
compose the object
the system needs to allow different representations for the objects that are being built

Example 1 - Vehicle Manufacturer.
Let us take the case of a vehicle manufacturer that, from a set of parts, can build a car, a
bicycle, a motorcycle or a scooter. In this case the Builder will become the VehicleBuilder. It
specifies the interface for building any of the vehicles in the list above, using the same set
of parts and a different set of rules for every type of type of vehicle. The ConcreteBuilders
will be the builders attached to each of the objects that are being under construction. The
Product is of course the vehicle that is being constructed and the Director is the
manufacturer and its shop.
Example 1 - Students Exams.
If we have an application that can be used by the students of a University to provide them
with the list of their grades for their exams, this application needs to run in different ways
depending on the user that is using it, user that has to log in. This means that, for example,
the admin needs to have some buttons enabled, buttons that needs to be disabled for the
student, the common user. The Builder provides the interface for building form depending
on the login information. The ConcreteBuilders are the specific forms for each type of user.
The Product is the final form that the application will use in the given case and the Director
is the application that, based on the login information, needs a specific form.
Specific problems and implementation
Builder and Abstract Factory
The Builder design pattern is very similar, at some extent, to the Abstract Factory pattern.
Thats why it is important to be able to make the difference between the situations when
one or the other is used. In the case of the Abstract Factory, the client uses the factorys
methods to create its own objects. In the Builders case, the Builder class is instructed on
how to create the object and then it is asked for it, but the way that the class is put
together is up to the Builder class, this detail making the difference between the two
patterns.
Common interface for products
In practice the products created by the concrete builders have a structure significantly
different, so if there is not a reason to derive different products a common parent class. This
also distinguishes the Builder pattern from the Abstract Factory pattern which creates
objects derived from a common type.

Prototype Pattern
Motivation
Todays programming is all about costs. Saving is a big issue when it comes to using
computer resources, so programmers are doing their best to find ways of improving the
performance When we talk about object creation we can find a better way to have new
objects: cloning. To this idea one particular design pattern is related: rather than creation it
uses cloning. If the cost of creating a new object is large and creation is resource intensive,
we clone the object.
The Prototype design pattern is the one in question. It allows an object to create customized
objects without knowing their class or any details of how to create them. Up to this point it
sounds a lot like the Factory Method pattern, the difference being the fact that for the
Factory the palette of prototypical objects never contains more than one object.
Intent
specifying the kind of objects to create using a prototypical instance
creating new objects by copying this prototype
Implementation
The pattern uses abstract classes, as we will see below and only three types of classes
making its implementation rather easy.

The classes participating to the Prototype Pattern are:
Client - creates a new object by asking a prototype to clone itself.
Prototype - declares an interface for cloning itself.
ConcretePrototype - implements the operation for cloning itself.
The process of cloning starts with an initialized and instantiated class. The Client asks for a
new object of that type and sends the request to the Prototype class. A ConcretePrototype,
depending of the type of object is needed, will handle the cloning through the Clone()
method, making a new instance of itself.
Here is a sample code for the Prototype pattern:
public interface Prototype {
public abstract Object clone ( );
}



public class ConcretePrototype implements Prototype {
public Object clone() {
return super.clone();
}
}

public class Client {

public static void main( String arg[] )
{
ConcretePrototype obj1= new ConcretePrototype ();
ConcretePrototype obj2 = ConcretePrototype)obj1.clone();
}

}
This example is rather trivial, but the real use of the pattern comes when we dont know
what were actually cloning. For example if we need the newly created object to be stored in
a hashtable we can use it like this:
// Violation of Likov's Substitution Principle
class Rectangle
{
protected int m_width;
protected int m_height;

public void setWidth(int width){
m_width = width;
}

public void setHeight(int height){
m_height = height;
}


public int getWidth(){
return m_width;
}

public int getHeight(){
return m_height;
}

public int getArea(){
return m_width * m_height;
}
}

class Square extends Rectangle
{
public void setWidth(int width){
m_width = width;
m_height = width;
}

public void setHeight(int height){
m_width = height;
m_height = height;
}

}

class LspTest
{
private static Rectangle getNewRectangle()
{
// it can be an object returned by some factory ...
return new Square();
}

public static void main (String args[])
{
Rectangle r = LspTest.getNewRectangle();

r.setWidth(5);
r.setHeight(10);
// user knows that r it's a rectangle.
// It assumes that he's able to set the width and height as
for the base class

System.out.println(r.getArea());
// now he's surprised to see that the area is 100 instead of
50.
}
}
Applicability & Examples
Use Prototype Pattern when a system should be independent of how its products are
created, composed, and represented, and:
Classes to be instantiated are specified at run-time
Avoiding the creation of a factory hierarchy is needed
It is more convenient to copy an existing instance than to create a new one.
Example 1
In building stages for a game that uses a maze and different visual objects that the
character encounters it is needed a quick method of generating the haze map using the
same objects: wall, door, passage, room... The Prototype pattern is useful in this case
because instead of hard coding (using new operation) the room, door, passage and wall
objects that get instantiated, CreateMaze method will be parameterized by various
prototypical room, door, wall and passage objects, so the composition of the map can be
easily changed by replacing the prototypical objects with different ones.
The Client is the CreateMaze method and the ConcretePrototype classes will be the ones
creating copies for different objects.
Example 2:
Suppose we are doing a sales analysis on a set of data from a database. Normally, we
would copy the information from the database, encapsulate it into an object and do the
analysis. But if another analysis is needed on the same set of data, reading the database
again and creating a new object is not the best idea. If we are using the Prototype pattern
then the object used in the first analysis will be cloned and used for the other analysis.
The Client is here one of the methods that process an object that encapsulates information
from the database. The ConcretePrototype classes will be classes that, from the object
created after extracting data from the database, will copy it into objects used for analysis.
Specific problems and implementation
Using a prototype manager
When the application uses a lot of prototypes that can be created and destroyed
dynamically, a registry of available prototypes should be kept. This registry is called the
prototype manager and it should implement operations for managing registered prototypes
like registering a prototype under a certain key, searching for a prototype with a given key,
removing one from the register, etc. The clients will use the interface of the prototype
manager to handle prototypes at run-time and will ask for permission before using the
Clone() method.
There is not much difference between an implementation of a prototype which uses a
prototype manager and a factory method implemented using class registration mechanism.
Maybe the only difference consists in the performance.
Implementing the Clone operation
A small discussion appears when talking about how deep or shallow a clone should be: a
deep clone clones the instance variables in the cloning object while a shallow clone shares
the instance variables between the clone and the original. Usually, a shallow clone is enough
and very simple, but cloning complex prototypes should use deep clones so the clone and
the original are independent, a deep clone needing its components to be the clones of the
complex objects components.
Initializing clones
There are cases when the internal states of a clone should be initialized after it is created.
This happens because these values cannot be passed to the Clone() method, that uses an
interface which would be destroyed if such parameters were used. In this case the
initialization should be done by using setting and resetting operations of the prototype class
or by using an initializing method that takes as parameters the values at which the clones
internal states should be set.
Hot points
Prototype Manager implemented usually as a hashtable keeping the object to clone. When
use it, prototype become a factory method which uses cloning instead of instantiation.
Deep Clones vs. Shallow Clones when we clone complex objects which contains other
objects, we should take care how they are cloned. We can clone contained objects also
(deep cloning) or we can the same reference for them, and to share them between cloned
container objects.
Initializing Internal States there are certain situations when objects need to be initialized
after they are created.

Object Pool
Motivation

Performance can be sometimes the key issue during the software development and the
object creation(class instantiation) is a costly step. While the Prototype pattern helps in
improving the performance by cloning the objects, the Object Pool pattern offer a
mechanism to reuse objects that are expensive to create.

Clients of an object pull "feel" like they are owners of a service although the service is
shared among many other clients.

Intent

-reuse and share objects that are expensive to create.

Implementation



Implementation involves the following objects:
Reusable - Wraps the limited resource, will be shared by several clients for a limited amount
of time.
Client - uses an instance of type Reusable.
ReusablePool - manage the reusable objects for use by Clients, creating and managing a
pool of objects.

When a client asks for a Reusable object, the pool performs the following actions:
- Search for an available Reusable object and if it was found it will be returned to the
client.
- If no Reusable object was found then it tries to create a new one. If this actions succeds
the new Reusable object will be returned to the client.
- If the pool was unable to create a new Reusable, the pool will wait until a reusable
object will be released.

The Client is responsible to request the Reusable object as well to release it to the pool. If
this action will not be performed the Reusable object will be lost, being considered
unavailable by the ResourcePool.

The clients are not aware that they are sharing the Reusable object. From the client poinf of
view they are the owners of a new object which comes from the Resource pool in the same
way that it comes from a factory or another creational design pattern. The only difference is
that the Client should mark the Reusable object as available, after it finishes to use it. It's
not about releasing the objects; for example if we work with databases, when a connection
is closed it's not necesarely distroyed, it means that it can be reused by another client.

Why to use it?

Basically, we'll use an object pool whenever there are several clients who needs the same
stateless resource which is expensive to create.

Applicability & Examples

Lets' take the example of the database connections. It's obviosly that opening too many
connections might affect the performance for several reasons:
Creating a connection is an expensive operation.
When there are too many connections opened it takes longer to create a new one and the
database server will become overloaded.

Here the object pool comes in to picture to manage the connections and provide a way to
reuse and share them. It can also limit the maximum number of objects that can be
created.



This pattern provide the following mechaninsm:

Connection - represent the object which is instantiated by the client. From the client
perspective this object is instantiated and it handles the database operations and it is the
only object visible to the client. The client is not aware that it uses some shared
connections. Internally this class does not contain any code for connecting to the database
and calls ConnectionPool.aquireImpl to get a ConnectionImpl object and then delegates the
request to ConnectionImpl.

ConnectionImpl is the object which implements the database operations which are exposed
by Connection for the client.

ConnectionPool is the main actor to manage the connections to the database. It keeps a list
of ConnectionImpl objects and instantiates new objects if this is required.

When the client needs to query the database it instantiate a new Connection object
specifing the database name and the call the query method which returns a set of records.
From the client point of view this is all.

When the Connection.Query methd is called it asks for a ConnectionImpl object from the
ConnectionPool. The ConnectionPool tries to find and return an unused object and if it
doesn't find it creates one. At this point the maximum number of connections can be limited
and if it was reached the pool cand wait until one will be available or return null. In the
query method the request is delegated to the ConnectionImpl object returned by the object
pool. Since the request is just delegated it's recomended to have the same method
signature in Connection and ConnectionImpl.

Specific problems and implementation

Singleton reusable pool - The reusable pool is implemented as a singleton. The reusable
pool should be accesible only to the Connection object.

1. Limited number of resources in the pool

The connection pool is responsable for sharing and reusing the resources. Sometimes the
resources have to be well managed only because they affects the performace, but there are
situations when the number of resources can not exceed a specific limit. In this case the
Resource pool check the number of instantiated resources and of the limit is reach it will
wait for a resource to be released, it will throw an exception or it will return a null value. In
any of the last 2 situations the Client should be notified that the action failed because there
are no available resources.

2. Handling situations when creating a new resource fails

There are many reasons when the ResourcePool.acquireConnectionImpl method fails to
return a resource. It might happens because there are not available resources or some
exception occured. Either way the client should be notified about his.

3. Syncronization

In order to work in a multithreading environment the methods that are used by differnt
threads should be synchronized. There are only three methonds in the ResourcePool object
that have to be synchronized:
- getInstance should be synchronized or should contain a synchronized block. For details
check the singleton multithreading implementation.
- acquireConnectionImpl - this menthod returns a resource and should be synchronized
not to return the same resource to two different clients running tin different threads.
- releaseConnectionImpl - this method release a resource. Ussually it doesn't have to be
synchronized a resource is allocated only by one client. Internally some blocks might need
to be synchronized(depending on the method implementation and the internal structures
used to keep the pool.).

4. Expired resources(unused but still reserved)

The main problem for the Object Pool Pattern is that the objects should be released by the
client when it finishes using them. There are plenty of examples when the client forget to
release the resources. Let's take the example the the database connections when
connection are not closed/released after they are used. This seems a minor problem but
there are many applications crushing for this reason.

In object pool can be implemented a mechanism to check when a specific resource was
used last time and if the time expired, to return it to the available resource pool.

Hot Points
- When the Object Pool pattern is used the objects should be marked as
available(released) by the client after they are used, so the pool will be aware about this.
This is the main drawback because the client should do this and it's a common situation
when database connection are not released afer they are used. To overcome this a
mechanism can be implemented to release resources if they are not used for a period of
time.
- Creating the resources might fail and this case should be treated carefully. When there
is no available resource(beacause the number is limited or creating a new one failed) the
client should be notified about it.

Conclusion

Althrough the object pool is handling the object instantiation it's main purpose is to provide
a way for the clients to reuse the objects like they are new objects, without being shared
and reused.

Behavioural Patterns
Chain of Responsibility
Motivation
In writing an application of any kind, it often happens that the event generated by one
object needs to be handled by another one. And, to make our work even harder, we also
happen to be denied access to the object which needs to handle the event. In this case
there are two possibilities: there is the beginner/lazy approach of making everything public,
creating reference to every object and continuing from there and then there is the expert
approach of using the Chain of Responsibility.
The Chain of Responsibility design pattern allows an object to send a command without
knowing what object will receive and handle it. The request is sent from one object to
another making them parts of a chain and each object in this chain can handle the
command, pass it on or do both. The most usual example of a machine using the Chain of
Responsibility is the vending machine coin slot: rather than having a slot for each type of
coin, the machine has only one slot for all of them. The dropped coin is routed to the
appropriate storage place that is determined by the receiver of the command.
Intent:
It avoids attaching the sender of a request to its receiver, giving this way other objects the
possibility of handling the request too.
The objects become parts of a chain and the request is sent from one object to another
across the chain until one of the objects will handle it.
Implementation
The UML diagram of classes below will help us understand better the way the Chain works.

In the diagram above some explanations are needed on what is the role of every class:
Handler - defines an interface for handling requests
RequestHandler - handles the requests it is responsible for
o If it can handle the request it does so, otherwise it sends the request to its successor
Client - sends commands to the first object in the chain that may handle the command
Here is how sending a request works in the application using the Chain of Responsibility: the
Client in need of a request to be handled sends it to the chain of handlers, which are classes
that extend the Handler class. Each of the handlers in the chain takes its turn at trying to
handle the request it receives from the client. If ConcreteHandler_i can handle it, then the
request is handled, if not it is sent to the handler ConcreteHandler_i+1, the next one in the
chain.
The classic example of the Chain of Responsibility's implementation is presented for us
below:

public class Request {
private int m_value;
private String m_description;

public Request(String description, int value)
{
m_description = description;
m_value = value;
}

public int getValue()
{
return m_value;
}

public String getDescription()
{
return m_description;
}
}

public abstract class Handler
{
protected Handler m_successor;
public void setSuccessor(Handler successor)
{
m_successor = successor;
}

public abstract void handleRequest(Request request);
}

public class ConcreteHandlerOne extends Handler
{
public void handleRequest(Request request)
{
if (request.getValue() < 0)
{ //if request is eligible handle it
System.out.println("Negative values are handled by
ConcreteHandlerOne:");
System.out.println("\tConcreteHandlerOne.HandleRequest :
" + request.getDescription()
+ request.getValue());
}
else
{
super.handleRequest(request);
}
}
}

public class ConcreteHandlerThree extends Handler
{
public void handleRequest(Request request)
{
if (request.getValue() >= 0)
{ //if request is eligible handle it
System.out.println("Zero values are handled by
ConcreteHandlerThree:");
System.out.println("\tConcreteHandlerThree.HandleRequest
: " + request.getDescription()
+ request.getValue());
}
else
{
super.handleRequest(request);
}
}
}

public class ConcreteHandlerTwo extends Handler
{
public void handleRequest(Request request)
{
if (request.getValue() > 0)
{ //if request is eligible handle it
System.out.println("Positive values are handled by
ConcreteHandlerTwo:");
System.out.println("\tConcreteHandlerTwo.HandleRequest :
" + request.getDescription()
+ request.getValue());
}
else
{
super.handleRequest(request);
}
}
}

public class Main
{
public static void main(String[] args)
{
// Setup Chain of Responsibility
Handler h1 = new ConcreteHandlerOne();
Handler h2 = new ConcreteHandlerTwo();
Handler h3 = new ConcreteHandlerThree();
h1.setSuccessor(h2);
h2.setSuccessor(h3);

// Send requests to the chain
h1.handleRequest(new Request("Negative Value ", -1));
h1.handleRequest(new Request("Negative Value ", 0));
h1.handleRequest(new Request("Negative Value ", 1));
h1.handleRequest(new Request("Negative Value ", 2));
h1.handleRequest(new Request("Negative Value ", -5));
}
}

Applicability & Examples
Having so many design patterns to choose from when writing an application, it's hard to
decide on which one to use, so here are a few situations when using the Chain of
Responsibility is more effective:
More than one object can handle a command
The handler is not known in advance
The handler should be determined automatically
Its wished that the request is addressed to a group of objects without explicitly specifying
its receiver
The group of objects that may handle the command must be specified in a dynamic way
Here are some real situations in which the Chain of Responsibility is used:
Example 1
In designing the software for a system that approves the purchasing requests.
In this case, the values of purchase are divided into categories, each having its own
approval authority. The approval authority for a given value could change at any time and
the system should be flexible enough to handle the situation.
The Client in the example above is the system in need of the answer to the approval. It
sends a request about it to an purchase approval authority. Depending on the value of the
purchase, this authority may approve the request or forward it to the next authority in the
chain.
For example lets say a request is placed for the purchase of a new keyboard for an office.
The value of the purchase is not that big, so the request is sent from the head of the office
to the head of the department and then to the materials department where it stops, being
handled locally. But if equipment for the whole department is needed then the request goes
form the head of the department, to materials department, to the purchase office and even
to the manager if the value is too big.
Example 2
In designing the software that uses a set of GUI classes where it is needed to propagate
GUI events from one object to another.
When an event, such as the pressing of a key or the click of the mouse, the event is needed
to be sent to the object that has generated it and also to the object or objects that will
handle it.
The Client is, of course, the object that has generated the event, the request is the event
and the handlers are the objects that can handle it. So, if we have a handler for the click of
the mouse, a handler for the pressing of the Enter key and a handler for the pressing of
the Delete key, that is the chain of handlers that take care of the events that are
generated.
Example 3
In designing a shipping system for electronic orders.
The steps to complete and handle the order differs form one order to another based on the
customer, the size of the order, the way of shipment, destination and more other reasons.
The business logic changes also as special cases appear, needing the system to be able to
handle all cases.
The Client, the electronic order in process, requests shipping based on a set of pieces of
information. Its request is turned by the system into a specific form, combining the steps to
completing and the details of handling, based on the input information. The system will send
this type of request through a chain of order-handlers until the input information that it
comes with matches the input the order-handles takes. When special cases appear, all that
is needed is a new handler to be added in the chain.
Specific problems and implementation
The classic implementation of the Chain of Responsibility is just the first step in applying the
pattern to our own application. Improvements based on the type of commands we are
handling are needed, in order to make the use of this pattern effective.
Representing requests
In real life each handler represents a system. And each system can handle specific requests
or requests common to more handlers. We should take this issue in consideration when we
implement this pattern. In the classical samples of the CoR found on the net you can see
that the request is generally represented by an integer. Of course in real life we can not use
primary data types as a request.
A clever design should be a flexible one. The best solution here is to create an interface a
super class Request (or and interface) where to the default behavior. Then if we need to
add a new handler and a specific request all we need is to extend the Request base class.
Of course this is not the only approach. Lets consider the shipping system example. Each
request will have to contain a large amount of data. Creating request examples for this
might be difficult. We can take some xml objects containing the data, generated during the
application flow (lets assume we already have the code implemented for that) and pass
them to each handler.
Or since the data was already saved in the database (lets assume that also) we can pass
only the ids of the involved objects and then each handler will take the data required from
db.
Unhandled requests
Unfortunately, the Chain doesn't guarantee that every command is handled, which makes
the problem worse, since unhandled commands propagate through the full length of the
chain, slowing down the application. One way to solve this is by checking if, at the end of
the chain, the request has been handled at least once, otherwise we will have to implement
handlers for all the possible requests that may appear.
Broken Chain
Sometimes we could forget to include in the implementation of the handleRequest method
the call to the successor, causing a break in the chain. The request isnt sent forward from
the broken link and so it ends up unhandled. A variation of the pattern can be made to send
the request to all the handlers by removing the condition from the handler and always
calling the successor.
The following implementation eliminates the Broken Chain problem. The implementation
moves the code to traverse the chain into the base class keeping the request handling in a
different method in the subclasses. The handleRequest method is declared as final in the
base class and is responsible to traverse the chain. Each Handler have to implement the
handleRequestImpl method, declared as abstract in the super class.

public abstract class Handler{
private Handler m_successor;

public void setSuccessor(Handler successor)
{
m_successor = successor;
}

protected abstract boolean handleRequestImpl(Request request);

public final void handleRequest(Request request)
{
boolean handledByThisNode = this.handleRequestImpl(request);
if (m_successor != null && !handledByThisNode)
{
m_successor.handleRequest(request);
}
}
}

protected boolean handleRequestImpl(Request request)
{
if (request.getValue() < 0)
{ //if request is eligible handle it
System.out.println("Negative values are handled by
ConcreteHandlerOne:");
System.out.println("\tConcreteHandlerOne.HandleRequest : " +
request.getDescription()
+ request.getValue());
return true;
}
else
{
return false;
}
}
The above implementation not only that eliminates the broken chain problem, but it also
offers an increased level of flexibility. Only by changing the handleRequest method we can
change the pattern to send to al handlers regardless the request handling:
public final void handleRequest(Request request)
{
boolean handledByThisNode = this.handleRequestImpl(request);
if (m_successor != null && !handledByThisNode)
m_successor.handleRequest(request);
}
Avoiding spam requests
For example, an improvement that we could find useful is avoiding sending spam
commands. This way, the concrete extension of the HandleRequest function will look like
this:
public void HandleRequest(int request)
{
if(isSpam(request))
{ // if the request is spam take spam-related actions
...
}
else
{ // request is not spam.
super.HandleRequest(request); // Pass message to next filter in
the chain.
}
}
Use on existing code
The last, but not least problem that the Chain of Responsibility creates to a programmer is
the fact that it is impossible to introduce the pattern into the existing classes without
modifying the source code and, even in the case where the pattern is already included in
the code, if new operations need to be added to the Handler, it is impossible to do that
without modifying the source code. So the basic idea is to decide from the start on whether
to use the pattern or not and if we do, what methods we need.
Hot points
The fundamental flaw of the pattern is the fact that it gets easily broken: if the programmer
forgets to call the next handler in the concreteHandler the request gets lost on the way. This
problem comes from the fact that the execution is not handled entirely by the superclass
and the call is triggered in the superclass.
When implementing the CoR pattern a special care should be taken for the request
representation. The request is not considered a distinctive part of the CoR pattern, but it is
still used in all the components of the pattern.
Another flaw of the Chain of Responsibility is the fact that some requests may end up
unhandled due to the wrong implementation of concrete handler, their propagation slowing
down the rest of the application. This means that extra care is needed when taking into
account the requests that may appear in the process.

Command Pattern

An object that contains a symbol, name or key that represents a list of commands, actions
or keystrokes. This is the definition of a macro, one that should be familiar to any
computer user. From this idea the Command design pattern was given birth.
The Macro represents, at some extent, a command that is built from the reunion of a set of
other commands, in a given order. Just as a macro, the Command design pattern
encapsulates commands (method calls) in objects allowing us to issue requests without
knowing the requested operation or the requesting object. Command design pattern
provides the options to queue commands, undo/redo actions and other manipulations.

Intent
- encapsulate a request in an object
- allows the parameterization of clients with different requests
- allows saving the requests in a queue

Implementation
The idea and implementation of the Command design pattern is quite simple, as we will see
in the diagram below, needing only few extra classes implemented.



The classes participating in the pattern are:
- Command - declares an interface for executing an operation;
- ConcreteCommand - extends the Command interface, implementing the Execute method
by invoking the corresponding operations on Receiver. It defines a link between the
Receiver and the action.
- Client - creates a ConcreteCommand object and sets its receiver;
- Invoker - asks the command to carry out the request;
- Receiver - knows how to perform the operations;

The Client asks for a command to be executed. The Invoker takes the command,
encapsulates it and places it in a queue, in case there is something else to do first, and the
ConcreteCommand that is in charge of the requested command, sending its result to the
Receiver.

Here is a sample code of a classic implementation of this pattern for placing orders for
buying and selling stocks:


The client creates some orders for buying and selling stocks (ConcreteCommands). Then the
orders are sent to the agent (Invoker).The agent takes the orders and place them to the
StockTrade system (Receiver). The agent keeps an internal queue with the order to be
placed. Let's assume that the StockTrade system is closed each Monday, but the agent
accepts orders, and queue them to be processed later on.
public interface Order {
public abstract void execute ( );
}

// Receiver class.
class StockTrade {
public void buy() {
System.out.println("You want to buy stocks");
}
public void sell() {
System.out.println("You want to sell stocks ");
}
}

// Invoker.
class Agent {
private m_ordersQueue = new ArrayList();

public Agent() {
}

void placeOrder(Order order) {
ordersQueue.addLast(order);
order.execute(ordersQueue.getFirstAndRemove());
}
}

//ConcreteCommand Class.
class BuyStockOrder implements Order {
private StockTrade stock;
public BuyStockOrder ( StockTrade st) {
stock = st;
}
public void execute( ) {
stock . buy( );
}
}

//ConcreteCommand Class.
class SellStockOrder implements Order {
private StockTrade stock;
public SellStockOrder ( StockTrade st) {
stock = st;
}
public void execute( ) {
stock . sell( );
}
}

// Client
public class Client {
public static void main(String[] args) {
StockTrade stock = new StockTrade();
BuyStockOrder bsc = new BuyStockOrder (stock);
SellStockOrder ssc = new SellStockOrder (stock);
Agent agent = new Agent();

agent.placeOrder(bsc); // Buy Shares
agent.placeOrder(ssc); // Sell Shares
}
}


Applicability & Examples
The applicability of the Command design pattern can be found in these cases below:
- parameterizes objects depending on the action they must perform
- specifies or adds in a queue and executes requests at different moments in time
- offers support for undoable actions (the Execute method can memorize the state and allow
going back to that state)
- structures the system in high level operations that based on primitive operations
- decouples the object that invokes the action from the object that performs the action. Due
to this usage it is also known as Producer - Consumer design pattern.

The example of the meal order at a restaurant is a very good one when trying to explain
better how the pattern works:
The waiter (Invoker) takes the order from the customer on his pad. The order is then
queued for the order cook and gets to the cook (Receiver) where it is processed.


In this case the actors in the scenario are the following: The Client is the customer. He
sends his request to the receiver through the waiter, who is the Invoker. The waiter
encapsulates the command (the order in this case) by writing it on the check and then
places it, creating the ConcreteCommand object which is the command itself. The Receiver
will be the cook that, after completing work on all the orders that were sent to him before
the command in question, starts work on it. Another noticeable aspect of the example is the
fact that the pad for the orders does not support only orders from the menu, so it can
support commands to cook many different items.

Just the same way we can consider the example of an auto-repair shop. People come in with
different cars that have different problems. The person at the front desk takes their
information and places the car in a queue for repair. The information on the order is
encapsulated in the paper the car owner will use when he comes back to pick up the fixed
car. At some point the car will become the first item in the queue and the mechanic will
repair it. Just as in the example above, the Client is the customer. The Invoker is the person
at the front desk that takes the information on the car and its problems, the
ConcreteCommand is the request for fixing the car and the Receiver is the mechanic.
The most used implementation of the command pattern is the one used to implement the
undo options in applications:

Let's consider a calculator application. The application represents the Client. The calculator
(Receiver) class is the main class used in the application to perform the commands. This
might be as well the document class if we have a text editor application and we want to
implement operations like copy/paste/etc.... When the application has to perform a
command it creates the command and sent it to the invoker. The invoker calls the execute
method of the command and adds it to a list containing all the commands. The execute
method of the command delegate the call to the Calculator object. When undo operations
are performed the invoker uses the list with all executed commands and calls for each one
the unexecuted method. The redo operation works in the same manner.

Specific problems and implementation

Now that we have understood how the pattern works, it's time to take a look at its
advantages and flaws, too.


The intelligence of a command
There are two extremes that a programmer must avoid when using this pattern:
1. The command is just a link between the receiver and the actions that carry out the
request
2. The command implements everything itself, without sending anything to the receiver.
We must always keep in mind the fact that the receiver is the one who knows how to
perform the operations needed, the purpose of the command being to help the client to
delegate its request quickly and to make sure the command ends up where it should.

Undo and redo actions
As mentioned above, some implementations of the Command design pattern include parts
for supporting undo and redo of actions. In order to do that a mechanism to obtain past
states of the Receiver object is needed; in order to achieve this there are two options:
- Before running each command a snapshot of the receiver state is stored in memory. This
does not require much programming effort but can not be always applied. For example
doing this in an image processing application would require storing images in memory after
each step, which is practically impossible.
- Instead of storing receiver objects states, the set of performed operations are stored in
memory. In this case the command and receiver classes should implement the inverse
algorithms to undo each action. This will require additional programming effort, but less
memory will be required. Sometimes for undo/redo actions the command should store more
information about the state of the receiver objects. A good idea in such cases is to use the
Memento Pattern.

Asynchronous Method Invocation
Another usage for the command design pattern is to run commands asynchronous in
background of an application. In this case the invoker is running in the main thread and
sends the requests to the receiver which is running in a separate thread. The invoker will
keep a queue of commands to be run and will send them to the receiver while it finishes
running them.

Instead of using one thread in which the receiver is running more threads can be created for
this. But for performance issues (thread creation is consuming) the number of threads
should be limited. In this case the invoker will use a pool of receiver threads to run
command asynchronously.


Adding new commands
The command object decouples the object that invokes the action from the object that
performs the action. There are implementations of the pattern in which the invoker
instantiates the concrete command objects. In this case if we need to add a new command
type we need to change the invoker as well. And this would violate the Open Close Principle
(OCP). In order to have the ability to add new commands with minimum of effort we have
to make sure that the invoker is aware only about the abstract command class or interface.

Using composite commands
When adding new commands to the application we can use the composite pattern to group
existing commands in another new command. This way, macros can be created from
existing commands.

Hot spot
The main advantage of the command design pattern is that it decouples the object that
invokes the operation from the one that know how to perform it. And this advantage must
be kept. There are implementations of this design pattern in which the invoker is aware of
the concrete commands classes. This is wrong making the implementation more tightly
coupled. The invoker should be aware only about the abstract command class.

Template Method

Motivation
If we take a look at the dictionary definition of a template we can see that a template is a
preset format, used as a starting point for a particular application so that the format does
not have to be recreated each time it is used.
On the same idea is the template method is based. A template method defines an algorithm
in a base class using abstract operations that subclasses override to provide concrete
behavior.
Intent
- Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
- Template Method lets subclasses redefine certain steps of an algorithm without letting
them to change the algorithm's structure.

Implementation
AbstractClass - defines abstract primitive operations that concrete subclasses define to
implement steps of an algorithm.
- implements a template method which defines the skeleton of an algorithm. The template
method calls primitive operations as well as operations defined in AbstractClass or those of
other objects.
ConcreteClass - implements the primitive operations to carry out subclass-specific steps of
the algorithm.
When a concrete class is called the template method code will be executed from the base
class while for each method used inside the template method will be called the
implementation from the derived class.

Applicability & Examples
The Template Method pattern should be used:
- to implement the invariant parts of an algorithm once and leave it up to subclasses to
implement the behavior that can vary.
- when refactoring is performed and common behavior is identified among classes. A
abstract base class containing all the common code (in the template method) should be
created to avoid code duplication.

Example - Application used by a travel agency.

Lets' assume we have to develop an application for a travel agency. The travel agency is
managing each trip. All the trips contain common behavior but there are several packages.
For example each trip contains the basic steps:
- The tourists are transported to the holiday location by plane/train/ships,...
- Each day they are visiting something
- They are returning back home.
So we create an abstract class containing each step as an abstract method and one concrete
and final method that calls all the abstracts methods. Then we create one superclass for
each package:
public class Trip {
public final void performTrip(){
doComingTransport();
doDayA();
doDayB();
doDayC();
doReturningTransport
}
public abstract void doComingTransport();
public abstract void doDayA();
public abstract void doDayB();
public abstract void doDayC();
public abstract void doReturningTransport();
}

public class PackageA extends Trip {
public void doComingTransport() {
System.out.println("The turists are comming by air ...");
}
public void doDayA() {
System.out.println("The turists are visiting the aquarium ...");
}
public void doDayB() {
System.out.println("The turists are going to the beach ...");
}
public void doDayC() {
System.out.println("The turists are going to mountains ...");
}
public void doReturningTransport() {
System.out.println("The turists are going home by air ...");
}
}
public class PackageB extends Trip {
public void doComingTransport() {
System.out.println("The turists are comming by train ...");
}
public void doDayA() {
System.out.println("The turists are visiting the mountain ...");
}
public void doDayB() {
System.out.println("The turists are going to the beach ...");
}
public void doDayC() {
System.out.println("The turists are going to zoo ...");
}
public void doReturningTransport() {
System.out.println("The turists are going home by train ...");
}
}

Specific problems and implementation
Concrete base class
It is not necessary to have the superclass as a abstract class. It can be a concrete class
containing a method (template method) and some default functionality. In this case the
primitive methods can not be abstract and this is a flaw because it is not so clear which
methods have to be overridden and which not.
A concrete base class should be used only when customizations hooks are implemented.
Template method can not be overridden
The template method implemented by the base class should not be overridden. The specific
programming language modifiers should be used to ensure this.
Customization Hooks
A particular case of the template method pattern is represented by the hooks. The hooks
are generally empty methods that are called in superclass (and does nothing because are
empty), but can be implemented in subclasses. Customization Hooks can be considered a
particular case of the template method as well as a totally different mechanism.
Usually a subclass can have a method extended by overriding id and calling the parent
method explicitly:
class Subclass extends Superclass
{
...
void something() {
// some customization code to extend functionality
super. something ();
// some customization code to extend functionality
}
}

Unfortunately it is easy to forget to call the super and this is forcing the developer to check
the existing code from the method in Superclass.
Instead of overriding some hook methods can be added. Then in the subclasses only the
hooks should be implemented without being aware of the method something:
class Superclass
{
...
protected void preSomethingHook(){}
protected void postSomethingHook(){}
void something() {
preSomethingHook();
// something implementation
postSomethingHook();
}
}
class Subclass extends Superclass
{
protected void preSomethingHook()
{
// customization code
}
protected void postSomethingHook()
{
// customization code
}
}

Minimizing primitive methods number
It's important when designing template methods to minimize the number of primitive
methods that a subclass must override in order to provide a clear an easy way to implement
concrete templates.
Naming Convetions
In order to identify the primitive methods is it better to use a specific naming convention.
For example the prefix do can be used for primitive methods. In a similar way the
customizations hooks can have prefixes like pre and post.
When methods that should be abstract or not
When there is a method in the base class that should contain default some code, but on the
other side it's necessary to be extended in the subclasses it should be split in 2 methods:
one abstract and one concrete. We can not rely in the fact that the subclasses will override
the method and will call the super implementation in it like this:
void something() {
super. something ();
// extending the method
}

Template Method and Strategy Design Pattern
The strategy pattern is with Template Method pattern. The difference consists in the fact
that Strategy uses delegation while the Template Methods uses the inheritance.

Hot points
Template method is using as an inverted controls structure, sometimes referred as the
Hollywood principle: from the superclass point of view: Don't call us, we'll call you. This
refers to the fact that instead of calling the methods from base class in the subclasses, the
methods from subclass are called in the template method from superclass.
Due to the above fact a special care should be paid to the access modifiers: the template
method should be implemented only in the base class, and the primitive method should be
implemented in the subclasses. A particular case of the template method is represented by
the customization hooks.

Interpreter

Motivation
The Interpreter is one of the Design Patterns published in the GoF which is not really used.
Ussualy the Interpreter Pattern is described in terms of formal grammars, like it was
described in the original form in the GoF but the area where this design pattern can be
applied can be extended.

Intent
- Given a language, define a representation for its grammar along with an interpreter that
uses the representation to interpret sentences in the language.
- Map a domain to a language, the language to a grammar, and the grammar to a
hierarchical object-oriented design
Implementation
The implementation of the Interpreter pattern is just the use of the composite pattern
applied to represent a grammar. The Interpreter defines the behaviour while the composite
defines only the structure.


Applicability & Examples
The Template Method pattern should be used:
- The Interpreter pattern is used exaustively in defining grammars, tokenize input and store
it.
- A specific area where Interpreter can be used are the rules engines.
- The Interpreter pattern can be used to add functionality to the composite pattern.

Example 1 - Roman Numerals Convertor
The classical example fot the interpreter pattern is the one of interpreting the roman
numerals. The expresion to be interpreted is a string which is put in the context. The
context consists of the remaining unparsed Roman Numeral string and of the result of the
numerral that are already parsed. The context is passed to one of four sub-interpreters
based on the type of interpreting(Thousand, Hundred, Ten, One). This example it's using
only TerminalExpressions.
The following participant classes are involved in this example: Context - keeps the current
string that has to be parsed and the decimal that contains the conversion already done.
Initially the context keeps the full string that has to be converted and 0 for the output
decimal.

Expression - Consists of the interpret method which receives the context. Based on the
current object it uses specific values for Thousand, Hundred, Ten, One and a specific
multiplier.

ThousandExpression, HundredExpression, TenExpression, OneExpression
(TerminalExpression) - Those classes are usued to define each specific expression.
Ussualy, the TerminalExpression classes implement the interpret method. In our case the
method is already defined in the base Expression class and each TerminalExpression class
defines its behaviour by implmenting the abstract methods: one, four(), five(), nine(),
multiplier(). It is a template method pattern.

Main(Client) - In our litle example this class is responsible to build the syntax tree
representing a specific sentence in the language defined by the grammar. After the syntax
tree is build the main method is invoking the interpret method.
public class Context {

private String input;
private int output;

public Context(String input)
{
this.input = input;
}

public String getInput()
{
return input;
}

public void setInput(String input)
{
this.input = input;
}

public int getOutput()
{
return output;
}

public void setOutput(int output)
{
this.output = output;
}
}

public abstract class Expression {

public void interpret(Context context)
{
if (context.getInput().length() == 0)
return;

if (context.getInput().startsWith(nine()))
{
context.setOutput(context.getOutput() + (9 * multiplier()));
context.setInput(context.getInput().substring(2));
}
else if (context.getInput().startsWith(four()))
{
context.setOutput(context.getOutput() + (4 * multiplier()));
context.setInput(context.getInput().substring(2));
}
else if (context.getInput().startsWith(five()))
{
context.setOutput(context.getOutput() + (5 * multiplier()));
context.setInput( context.getInput().substring(1));
}

while (context.getInput().startsWith(one()))
{
context.setOutput(context.getOutput() + (1 * multiplier()));
context.setInput(context.getInput().substring(1));
}
}

public abstract String one();
public abstract String four();
public abstract String five();
public abstract String nine();
public abstract int multiplier();

}

public class ThousandExpression extends Expression{

public String one() { return "M"; }
public String four(){ return " "; }
public String five(){ return " "; }
public String nine(){ return " "; }
public int multiplier() { return 1000; }
}

public class HundredExpression extends Expression{
public String one() { return "C"; }
public String four(){ return "CD"; }
public String five(){ return "D"; }
public String nine(){ return "CM"; }
public int multiplier() { return 100; }
}

public class TenExpression extends Expression{
public String one() { return "X"; }
public String four(){ return "XL"; }
public String five(){ return "L"; }
public String nine(){ return "XC"; }
public int multiplier() { return 10; }
}

public class OneExpression extends Expression{
public String one() { return "I"; }
public String four(){ return "IV"; }
public String five(){ return "V"; }
public String nine(){ return "IX"; }
public int multiplier() { return 1; }
}

public class MainInterpreter {

/**
* @param args
*/
public static void main(String[] args) {

String roman = "MCMXXVIII";
Context context = new Context(roman);

// Build the 'parse tree'
ArrayList<Expression> tree = new ArrayList<Expression>();
tree.add(new ThousandExpression());
tree.add(new HundredExpression());
tree.add(new TenExpression());
tree.add(new OneExpression());

// Interpret
for (Iterator it = tree.iterator(); it.hasNext();)
{
Expression exp = (Expression)it.next();
exp.interpret(context);
}

System.out.println(roman + " = " +
Integer.toString(context.getOutput()));
}
}

Example 2 - Rule Validator
This example can be used to validate some conditions. Each expression is interpreted and
the output for each expression is a boolean value. The following classes and entities are
involved:

String(Context) - The String is used as a context. The string that has to be interpreted is
parsed.

Expression - An abstract class with an abstract method called interpret.

TerminalExpression - This is the terminal expression. Only one terminal expression class
is defined in our example and it returns true if a token was found there.

AlternationExpression, SequenceExpression(NonTerminalExpressions) -
Implements logical operators(OR, AND) between 2 terminal or non terminal expressions.

Main(Client) - builds the abstract tree and call the interpret method of the Interpreter
tree.

public abstract class Expression {
abstract public boolean interpret(String str);
}

public class TerminalExpression extends Expression {

private String literal = null;

public TerminalExpression(String str) {
literal = str;
}

public boolean interpret(String str) {
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens()) {
String test = st.nextToken();
if (test.equals(literal)) {
return true;
}
}
return false;
}
}

public class OrExpression extends Expression{
private Expression expression1 = null;
private Expression expression2 = null;

public OrExpression(Expression expression1, Expression expression2) {
this.expression1 = expression1;
this.expression2 = expression2;
}

public boolean interpret(String str) {
return expression1.interpret(str) || expression2.interpret(str);
}
}

public class AndExpression extends Expression{

private Expression expression1 = null;
private Expression expression2 = null;

public AndExpression(Expression expression1, Expression expression2) {
this.expression1 = expression1;
this.expression2 = expression2;
}

public boolean interpret(String str) {
return expression1.interpret(str) && expression2.interpret(str);
}
}

public class Main {

/**
* this method builds the interpreter tree
* It defines the rule "Owen and (John or (Henry or Mary))"
* @return
*/
static Expression buildInterpreterTree()
{
// Literal
Expression terminal1 = new TerminalExpression("John");
Expression terminal2 = new TerminalExpression("Henry");
Expression terminal3 = new TerminalExpression("Mary");
Expression terminal4 = new TerminalExpression("Owen");

// Henry or Mary
Expression alternation1 = new OrExpression(terminal2, terminal3);

// John or (Henry or Mary)
Expression alternation2 = new OrExpression(terminal1, alternation1);

// Owen and (John or (Henry or Mary))
return new AndExpression(terminal4, alternation2);
}


/**
* main method - build the interpreter
* and then interpret a specific sequence
* @param args
*/
public static void main(String[] args) {

String context = "Mary Owen";

Expression define = buildInterpreterTree();

System.out.println(context + " is " + define.interpret(context));
}
}

Conclusion
The Interpreter pattern has a limited area where it can be applied. We can dsicuss the
Interpreter pattern only in terms of formal grammars but in this area there are better
solutions and this is the reason why this pattern is not so frequenlty used. This pattern can
be applied for parssing light expressions defined in simple grammars and sometimes in
simple rule engines.

Iterator
Motivation
One of the most common data structures in software development is what is generic called
a collection. A collection is just a grouping of some objects. They can have the same type or
they can be all cast to a base type like object. A collection can be a list, an array, a tree and
the examples can continue.

But what is more important is that a collection should provide a way to access its elements
without exposing its internal structure. We should have a mechanism to traverse in the
same way a list or an array. It doesn't matter how they are internally represented.

The idea of the iterator pattern is to take the responsibility of accessing and passing trough
the objects of the collection and put it in the iterator object. The iterator object will maintain
the state of the iteration, keeping track of the current item and having a way of identifying
what elements are next to be iterated.
Intent
Provide a way to access the elements of an aggregate object sequentially without exposing
its underlying representation.

The abstraction provided by the iterator pattern allows you to modify the collection
implementation without making any changes outside of collection. It enables you to create a
general purpose GUI component that will be able to iterate through any collection of the
application.
Implementation

Applicability & Examples
The iterator pattern allow us to:
access contents of a collection without exposing its internal structure.
support multiple simultaneous traversals of a collection.
provide a uniform interface for traversing different collection.

Example 1: This exmple is using a collection of books and it uses an iterator to iterate
through the collection. The main actors are:
IIterator - This interface represent the AbstractIterator, defining the iterator
BookIterator - This is the implementation of Iterator(implements the IIterator interface)
IContainer - This is an interface defining the Agregate
BooksCollection - An implementation of the collection
Here is the code for the abstractions IIterator and IContainer:

interface IIterator
{
public boolean hasNext();
public Object next();
}

interface IContainer
{
public IIterator createIterator();
}

And here is the code for concrete classes for iterator and collection. Please note that the
concrete iterator is an nested class. This way it can access all the members of the collection
and it is encapsulated so other classes can not access the BookIterator. All the classes are
not aware of BookIterator they uses the IIterator:

class BooksCollection implements IContainer
{
private String m_titles[] = {"Design Patterns","1","2","3","4"};

public IIterator createIterator()
{
BookIterator result = new BookIterator();
return result;
}


private class BookIterator implements IIterator
{
private int m_position;

public boolean hasNext()
{
if (m_position < m_titles.length)
return true;
else
return false;
}
public Object next()
{
if (this.hasNext())
return m_titles[m_position++];
else
return null;
}
}
}


Example 2: Java collection framework

Example 3: .NET collection framework


Specific problems and implementation
Iterator and multithreading
Several problems may appear when collections are added from different threads. First of all
let's see which the basic steps when using an iterator are:
Step one: the collection return a new iterator (using in our example the createIterator
method). Usually this step is not affected when it is used in multithreading environments
because it returns a new iterator object.
Step two: The iterator is used for iterating through the objects. Since the iterators are
different objects this step is not a problematic one in multithreading environments.
It seems that the iterator does not raise special problems when a collection is used from
different threads. Of course here we are talking about an "seems". To reformulate the
iterator does not raise special problems when the collection used from different threads as
long the collection is not changed.

Let's analyze each case:
A new element is added to the collection (at the end). The iterator should be aware of the
new size of the collection and to iterate till the end.
A new element is added to the collection before the current element. In this case all the
iterators of the collection should be aware of this.
The same actions should occur when an element is removed from the collection. The
iterators should be aware of the changes.

The main task when creating a multithreading iterator is to create a robust iterator (that
allows insertions and deletions without affection transversal). Then the blocks which are
changing or accessing resources changed by another thread have to be synchronized.

External vs. internal iterators.
External Iterators - when the iteration is controlled by the collection object we say that
we have an external Iterator.

In languages like .net on java it's very easy to create external iterators. In our classical
implementation an external iterator is implemented. In the following example an external
iterator is used:
// using iterators for a clloection of String objects:
// using in a for loop
for (Iterator it = options.iterator(); it.hasNext(); ) {
String name = (String)it.next();
System.out.println(name);
}

// using in while loop
Iterator name = options.iterator();
while (name.hasNext() ){
System.out.println(name.next() );
}

// using in a for-each loop (syntax available from java 1.5 and above)
for (Object item : options)
System.out.println(((String)item));

Internal Iterators - When the iterator controls it we have an internal iterator

On the other side implementing and using internal iterators is really difficult. When an
internal iterator is used it means that the code is be run is delegated to the aggregate
object. For example in languages that offer support for this is easy to call internal iterators:
collection do: [:each | each doSomething] (Smalltalk)

The main idea is to pass the code to be executed to the collection. Then the collection will
call internally the doSomething method on each of the components. In C++ it's possible to
send the doMethod method as a pointer. In C# .NET or VB.NET it is possible to send the
method as a delegate. In java the Functor design pattern has to be used. The main idea is
to create a base Interface with only one method (doSomething). Then the method will be
implemented in a class which implements the interface and the class will be passed to the
collection to iterate. For more details see the Functor design pattern.
Who defines the traversal algorithm?
The algorithm for traversing the aggregate can be implemented in the iterator or in the
aggregate itself. When the traversal algorithm is defined in the aggregate, the iterator is
used only to store the state of the iterator. This kind of iterator is called a cursor because it
points to the current position in the aggregate.

The other option is to implement the traversal algorithm in the iterator. This option offers
certain advantages and some disadvantages. For example it is easier to implement different
algorithms to reuse the same iterators on different aggregates and to subclass the iterator
in order to change its behavior. The main disadvantage is that the iterator will have to
access internal members of the aggregate. In Java and .NET this can be done, without
violating the encapsulation principle, by making the iterator an inner class of the aggregate
class.

Robust Iterators
- Can the aggregate be modified while a traversal is ongoing? An iterator that allows
insertion and deletions without affecting the traversal and without making a copy of the
aggregate is called a robust iterator. A robust iterator will make sure that when elements
are added or removed from an aggregate during iteration; elements are not accessed twice
or ignored.

Lets' say we don't need a robust iterator. If the aggregate can not be modified (because the
iteration is started), it should be made explicitly, meaning that the client should be aware of
it. We can just return a false value what an element is added to the collection stating that
the operation has failed, or we can throw an exception.

An alternative solution is to add functions to change the aggregate in the iterator itself. For
example we can add the following methods to our iterator:
bool remove();
bool insertAfer();
bool insertBefore();
In the case when this solution is chosen the iterator handles the changes of the aggregator.
In this case the operation to change the iteration should be added to the iterator interface
or base class not to the implementation only, in order to have a general mechanism for the
entire application.
Mechanism provided by the programming language
The iterator pattern can be implemented from scrach in Java or .NET, but there is already
built-in support for Iterator Pattern (IEnumerator/IEnumerable in .NET and
Iterator/Collection in JAVA).
Hot Spot
External vs. internal iterators - In languages like Java, C#, VB .NET, C++ is very easy to
use external iterators.
Who defines the traversal algorithm? - The aggregate can implement it or the iterator
as well. Usually the algorithm is defined in the iterator.
Robust Iterators - Can the aggregate be modified while a traversal is ongoing?
Multithreading iterators - First of all multithreading iterators should be robust iterators.
Second of all they should work in multithreading environments.

Mediator Pattern

Motivation
In order to have a good object oriented design we have to create lots of classes interacting
one with each other. If certain principles are not applied the final framework will end in a
total mess where each object relies on many other objects in order to run. In order to avoid
tight coupled frameworks, we need a mechanism to facilitate the interaction between
objects in a manner in that objects are not aware of the existence of other objects.
Let's take the example of a screen. When we create it we add all sort of controls to the
screen. This control need to interact with all the other control. For example when a button is
pressed it must know if the data is valid in other controls. As you have seen if you created
different applications using forms you don't have to modify each control class each time you
add a new control to the form. All the operations between controls are managed by the form
class itself. This class is called mediator.
Intent
Define an object that encapsulates how a set of objects interact. Mediator promotes loose
coupling by keeping objects from referring to each other explicitly, and it lets you vary their
interaction independently.

Implementation


Participants
The participants classes in this pattern are:
Mediator - defines an interface for communicating with Colleague objects.
ConcreteMediator - knows the colleague classes and keep a reference to the colleague
objects.
- implements the communication and transfer the messages between the colleague classes
Colleague classes - keep a reference to its Mediator object
- communicates with the Mediator whenever it would have otherwise communicated with
another Colleague.


Applicability
According to Gamma et al, the Mediator pattern should be used when:
a set of objects communicate in well-defined but complex ways. The resulting
interdependencies are unstructured and difficult to understand.
reusing an object is difficult because it refers to and communicates with many other objects.
a behavior that's distributed between several classes should be customizable without a lot of
subclassing.

Examples
Example 1 - GUI Libraries
The mediator example is one pattern that is already used in many applications. One of the
examples is represented by the Dialog classes in GUI applications frameworks. A Dialog
window is a collection of graphic and non-graphic controls. The Dialog class provides the
mechanism to facilitate the interaction between controls. For example, when a new value is
selected from a ComboBox object a Label has to display a new value. Both the ComboBox
and the Label are not aware of each other structure and all the interaction is managed by
the Dialog object. Each control is not aware of the existence of other controls.
Example 2 - Chat application
The chat application is another example of the mediator pattern. In a chat application we
can have several participants. It's not a good idea to connect each participant to all the
others because the number of connections would be really high, there would be technical
problems due to proxies and firewalls, etc... . The most appropriate solution is to have a
hub where all participants will connect; this hub is just the mediator class.
Participants:
Chatroom(Mediator) - Defines the interface for interacting with participants
ChatroomImpl (ConcreteMediator) - implements the operations defined by the
Chatroom interface. The operations are managing the interactions between the objects:
when one participant sends a message, the message is sent to the other participants.
Participant(Collegue) - defines an interface for the participants.
HumanParticipant, Bot (ConcreteCollegue) - implements participants; the participant
can be a human or a bot, each one having a distinct implementation but implementing the
same interface. Each participant will keep only a reference to the mediator.
Specific problems and implementation
Abstract Mediators
There is no need to create an Abstract Mediator class or an interface as long as the
colleagues are going to use only one mediator. The definition of an abstract Mediator is
required only if the colleagues needs to work with different mediators.
Communication between mediators and colleagues
There are different ways to realize the communication between the colleagues and its
mediator:
One of the most used methods is to use the Observer pattern. The mediator can be also an
observer and the Colleagues can be implement an observable object. Each time an change
is made in the state of the observable object, the observer(mediator) gets notified and it
notify all other colleagues objects.
Alternative methods can be used to send messages to the mediator. For example a simple
delegation can be used and specialised methods can be exposed by the mediator
In more complex implementations asynchronous messages can be added to to a message
queue, from where they can be picked up by the mediator object
Complexity of Mediator object
The mediator object handles all the interaction between the participants objects. One
potential problem is complexity of the mediator when the number of participants is a high
and the different participant classes is high. If you created custom dialogs for GUI
applications you remember that after some time the dialogs classes become really complex
because they had to manage a lot of operations.

Consequences
As with most design patterns, there are both advantages and disadvantages of using the
Mediator Patern. The following section will briefly outline a few of these issues.
Advantages
Comprehension - The mediator encapsulate the logic of mediation between the colleagues.
From this reason it' more easier to understand this logic since it is kept in only one class.
Decoupled Colleagues - The colleague classes are totally decoupled. Adding a new
colleague class is very easy due to this decoupling level.
Simplified object protocols - The colleague objects need to communicate only with the
mediator objects. Practically the mediator pattern reduce the required communication
channels(protocols) from many to many to one to many and many to one.
Limits Subclassing - Because the entire communication logic is encapsulated by the
mediator class, when this logic need to be extended only the mediator class need to be
extended.
Disadvantages
Complexity - in practice the mediators tends to become more complex and complex. A
good practice is to take care to make the mediator classes responsible only for the
communication part. For example when implementing different screens the the screen class
should not contain code which is not a part of the screen operations. It should be put in
some other classes.

Related Patterns
There are a few design patterns that are closely related to the Mediator pattern and are
often used in conjunction with it.
Facade Pattern - a simplified mediator becomes a facade pattern if the mediator is the
only active class and the colleagues are passive classes. A facade pattern is just an
implementation of the mediator pattern where mediator is the only object triggering and
invoking actions on passive colleague classes. The Facade is being call by some external
classes.
Adapter Pattern - the mediator patter just "mediate" the requests between the colleague
classes. It is not supposed to change the messages it receives and sends; if it alters those
messages then it is an Adapter pattern.
Observer Pattern - the observer and mediator are similar patterns, solving the same
problem. The main difference between them is the problem they address. The observer
pattern handles the communication between observers and subjects or subject. It's very
probable to have new observable objects added. On the other side in the mediator pattern
the mediator class is the the most likely class to be inherited.
Known Uses
In the following section, we'll discuss some real-world uses of the Mediator pattern. You'll
find the Mediator in many situations where there are many components that must interact
with one another in complex ways. User Interfaces
Maybe the mediator pattern is mostly used in the user interfaces. Almost any GUI
framework is build around it. Like discussed before, the classes representing forms (Dialog,
Form,... ) represents the the mediator while each control represents a colleague. The form
class provides the mechanism to facilitate the interaction between controls; an inherited
class is created each time a new screen is created and the specific code is written in this
class. This way, the controls communication is mediated by this form class. Java Message
Service
The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API for
sending messages between two or more clients. The JMS API supports 2 models. One of
them is the publish-subscribe model. It is an implementation of the mediator pattern. The
messages can be publisehd based on a particular topic. The publisher has to create a
subscription to which different subscribers may subscribe. Zero or more subscribers may
subscribe to receive messages on a particular message topic. The publisher and the
subscriber doesn't know one about eachother, the subscriber can be even inactive. In this
case the subscriber receives the messages when it will become active.
Conclusion
The mediator pattern is used to takes the role of a hub or router and facilitates the
communication between many classes. A similarity can be made with the database systems.
The mediator transform a hard to implement relation of many to many, where each calls
has to communicate with each other class, in 2 relations, easy to implement, of many to
one and one to many, where the communication is handled by the mediator class.

Memento Pattern
Motivation
It is sometimes necessary to capture the internal state of an object at some point and have
the ability to restore the object to that state later in time. Such a case is useful in case of
error or failure. Consider the case of a calculator object with an undo operation such a
calculator could simply maintain a list of all previous operation that it has performed and
thus would be able to restore a previous calculation it has performed. This would cause the
calculator object to become larger, more complex, and heavyweight, as the calculator object
would have to provide additional undo functionality and should maintain a list of all previous
operations. This functionality can be moved out of the calculator class, so that an external
(let's call it undo manager class) can collect the internal state of the calculator and save it.
However providing the explicit access to every state variable of the calculator to the restore
manager would be impractical and would violate the encapsulation principle.
Intent
The intent of this pattern is to capture the internal state of an object without violating
encapsulation and thus providing a mean for restoring the object into initial state when
needed.
Implementation
The figure below shows a UML class diagram for the Memento Pattern:

Memento
o Stores internal state of the Originator object. The state can include any number of state
variables.
o The Memento must have two interfaces, an interface to the caretaker. This interface must
not allow any operations or any access to internal state stored by the memento and thus
honors encapsulation. The other interface is to the originator and allows the originator to
access any state variables necessary to for the originator to restore previous state.
Originator
o Creates a memento object capturing the originators internal state.
o Use the memento object to restore its previous state.
Caretaker
o Responsible for keeping the memento.
o The memento is opaque to the caretaker, and the caretaker must not operate on it.
A Caretaker would like to perform an operation on the Originator while having the possibility
to rollback. The caretaker calls the createMemento() method on the originator asking the
originator to pass it a memento object. At this point the originator creates a memento
object saving its internal state and passes the memento to the caretaker. The caretaker
maintains the memento object and performs the operation. In case of the need to undo the
operation, the caretaker calls the setMemento() method on the originator passing the
maintained memento object. The originator would accept the memento, using it to restore
its previous state.
Applicability & Examples
The memento pattern is used when a snapshot of an object's state must be captured so that
it can be restored to that state later and in situations where explicitly passing the state of
the object would violate encapsulation.

Example - Simple Calculator with Undo Operation.
This simple example is a calculator that finds the result of addition of two numbers, with the
additional option to undo last operation and restore previous result.

Source: Click here to see java source code

Specific problems and implementation
Database Transactions
Transactions are operations on the database that occur in an atomic, consistent, durable,
and isolated fashion. A transaction can contain multiple operations on the database; each
operation can succeed or fail, however a transaction guarantees that if all operations
succeed, the transaction would commit and would be final. And if any operation fails, then
the transaction would fail and all operations would rollback and leave the database as if
nothing has happened.
This mechanism of rolling back uses the memento design pattern. Consider an object
representing a database table, a transaction manager object which is responsible of
performing transactions must perform operations on the table object while having the ability
to undo the operation if it fails, or if any operation on any other table object fails. To be able
to rollback, the transaction manager object would ask the table object for a memento before
performing an operation and thus in case of failure, the memento object would be used to
restore the table to its previous state.


Consequences
Memento protects encapsulation and avoids exposing originator's internal state and
implementation. It also simplifies originator code such that the originator does not need to
keep track of its previous state since this is the responsibility of the CareTaker.
Using the memento pattern can be expensive depending on the amount of state information
that has to be stored inside the memento object. In addition the caretaker must contain
additional logic to be able to manage mementos.
Related Patterns
Command Pattern - Commands can use mementos to maintain state for undoable
operations.
Known Uses
Undo and restore operations in most software.
Database transactions discussed earlier.

Visitor Pattern
Motivation
Collections are data types widely used in object oriented programming. Often collections
contain objects of different types and in those cases some operations have to be performed
on all the collection elements without knowing the type.
A possible approach to apply a specific operation on objects of different types in a collection
would be the use if blocks in conjunction with 'instanceof' for each element. This approach is
not a nice one, not flexible and not object oriented at all. At this point we should think to
the Open Close principle and we should remember from there that we can replace if blocks
with an abstract class and each concrete class will implement its own operation.
Intent
Represents an operation to be performed on the elements of an object structure.
Visitor lets you define a new operation without changing the classes of the elements on
which it operates.
Implementation

The participants classes in this pattern are:

Visitor - This is an interface or an abstract class used to declare the visit operations for all
the types of visitable classes. Usually the name of the operation is the same and the
operations are differentiated by the method signature: The input object type decides which
of the method is called.
ConcreteVisitor - For each type of visitor all the visit methods, declared in abstract visitor,
must be implemented. Each Visitor will be responsible for different operations. When a new
visitor is defined it has to be passed to the object structure.
Visitable - is an abstraction which declares the accept operation. This is the entry point
which enables an object to be "visited" by the visitor object. Each object from a collection
should implement this abstraction in order to be able to be visited.
ConcreteVisitable - Those classes implements the Visitable interface or class and defines
the accept operation. The visitor object is passed to this object using the accept operation.
ObjectStructure - This is a class containing all the objects that can be visited. It offers a
mechanism to iterate through all the elements. This structure is not necessarily a collection.
In can be a complex structure, such as a composite object.
Applicability & Examples
The visitor pattern is used when:
Similar operations have to be performed on objects of different types grouped in a structure
(a collection or a more complex structure).
There are many distinct and unrelated operations needed to be performed. Visitor pattern
allows us to create a separate visitor concrete class for each type of operation and to
separate this operation implementation from the objects structure.
The object structure is not likely to be changed but is very probable to have new operations
which have to be added. Since the pattern separates the visitor (representing operations,
algorithms, behaviors) from the object structure it's very easy to add new visitors as long as
the structure remains unchanged.
Example 1 - Customers Application.
We want to create a reporting module in our application to make statistics about a group of
customers. The statistics should made very detailed so all the data related to the customer
must be parsed. All the entities involved in this hierarchy must accept a visitor so the
CustomerGroup, Customer, Order and Item are visitable objects.
In the example we can see the following actors:
IVisitor and IVisitable interfaces
CustomerGroup, Customer, Order and Item are all visitable classes. A CustomerGroup
represents a group of customers, each Customer can have one or more orders and each
order can have one ore more Items.
GeneralReport is a visitor class and implements the IVisitor interface.
Source: Click here to see java source code


Specific problems and implementation
Tight Coupled Visitable objects
The classic implementation of the Visitor pattern have a major drawback because the type
of visitor methods has to be known in advance. The Visitor interface can be defined using
polymorphic methods or methods with different names:
public interface IVisitor {
public void visit(Customer customer);
public void visit(Order order);
public void visit(Item item);
}

public interface IVisitor {
public void visitCustomer(Customer customer);
public void visitOrder(Order order);
public void visitItem(Item item);
}
However this type should be known in advance. When a new type is added to the structure
a new method should be added to this interface and all existing visitors have to be changed
accordingly. A pair method is written in the concrete Visitable objects:
public class Customer implements IVisitable{
public void accept(IVisitor visitor)
{
visitor.visit(this);
}
}
It doesn't really matters if the polymorphic methods with the same name but different
signatures are used or not, because in either way the type is known at compile time sot for
each new visitable object this method must be implemented accordingly. The main
advantage of the fact that new visitors can be easily added is compensated by the fact that
the addition of new visitable objects is really hard.

Visitor Pattern using Reflection
Reflection can be used to overcome the main drawback of the visitor pattern. When the
standard implementation of visitor pattern is used the method to invoke is determined at
runtime. Reflection is the mechanism used to determine the method to be called at compile-
time. This way the visitable object will use the same code in the accept method. This code
can be moved in an abstraction so the IVisitable interface will be transformed to an
advanced class.
Let's take our example. We need to add a new visitable class in our structure, called
Product. We should modify the IVisitor interface to add a visitProduct method. But changing
an interface is one of the worth things that can be done. Usually, interfaces are extended by
lots of classes changing the interface means changing the classes. Maybe we have lots of
visitors but we don't want to change all of them, we need only another report.
In this case we start from the idea that we should keep the interface unchanged. The
solution is to replace the interface with an abstract class and to add an abstract method
called defaultVisit. The defaultVisit will be implemented by each new concrete visitor, but
the interface and old concrete visitors will remain unchanged.
The code is very simple: the visit(Object object) method check if there is visit method for
the specific object. If there is not an available visit the call is delegated to the defaultVisit
method:
public abstract class Visitor {

public abstract void visit(Customer customer);
public abstract void visit(Order order);
public abstract void visit(Item item);
public abstract void defaultVisit(Object object);

public void visit(Object object) {
try
{
Method downPolymorphic =
object.getClass().getMethod("visit",
new Class[] { object.getClass() });

if (downPolymorphic == null) {
defaultVisit(object);
} else {
downPolymorphic.invoke(this, new Object[]
{object});
}
}
catch (NoSuchMethodException e)
{
this.defaultVisit(object);
}
catch (InvocationTargetException e)
{
this.defaultVisit(object);
}
catch (IllegalAccessException e)
{
this.defaultVisit(object);
}
}
}
Another point that should be marked is the defaultVisit method: We should visit only classes
we know:
public void defaultVisit(Object object)
{
// if we don't know the class we do nothing
if (object.getClass().equals(Product.class))
{
System.out.println("default visit: "
+ object.getClass().getSimpleName());
itemsNo++;
}
}

Statefull Visitors
The visitors objects can be complex objects and can maintain a context during a traversal.

Encapsulation of visitable objects
The behavior is defined in the visitor itself and the objects structure is represented by
visitable objects. The Visitor needs to access data kept by visitable objects so practically the
pattern forces to expose from visitable objects the data required in the visitor, using public
methods.
Visitors and Iterators
The iterator pattern and visitor pattern has the same benefit, they are used to traverse
object structures. The main difference is that the iterator is intended to be used on
collections. Usually collections contain objects of the same type. The visitor pattern can be
used on complex structure such as hierarchical structures or composite structures. In this
case the accept method of a complex object should call the accept method of all the child
objects.
Another difference is operation performed on the objects: In one case the visitor defines the
operations that should be performed, while the iterator is used by the client to iterate
through the objects form a collection and the operations are defined by the client itself.
Visitors and Composites
The visitor pattern can be used in addition with the composite pattern. The object structure
can be a composite structure. In this case in the implementation of the accept method of
the composite object the accept methods of the component object has to be invoked.
Hot Points:
The visitor pattern is a great way to provide a flexible design for adding new visitors to
extend existing functionality without changing existing code
The Visitor pattern comes with a drawback: If a new visitable object is added to the
framework structure all the implemented visitors need to be modified. The separation of
visitors and visitable is only in one sense: visitors depend of visitable objects while visitable
are not dependent of visitors.
Part of the dependency problems can be solved by using reflection with a performance cost.

Observer Pattern
Motivation
We can not talk about Object Oriented Programming without considering the state of the
objects. After all object oriented programming is about objects and their interaction. The
cases when certain objects need to be informed about the changes occured in other objects
are frequent. To have a good design means to decouple as much as possible and to reduce
the dependencies. The Observer Design Pattern can be used whenever a subject has to be
observed by one or more observers.
Let's assume we have a stock system which provides data for several types of client. We
want to have a client implemented as a web based application but in near future we need to
add clients for mobile devices, Palm or Pocket PC, or to have a system to notify the users
with sms alerts. Now it's simple to see what we need from the observer pattern: we need to
separate the subject(stocks server) from it's observers(client applications) in such a way
that adding new observer will be transparent for the server.
Intent
Defines a one-to-many dependency between objects so that when one object changes state,
all its dependents are notified and updated automatically.

Implementation
The participants classes in this pattern are:

Observable - interface or abstract class defining the operations for attaching and de-
attaching observers to the client. In the GOF book this class/interface is known as Subject.
ConcreteObservable - concrete Observable class. It maintain the state of the object and
when a change in the state occurs it notifies the attached Observers.
Observer - interface or abstract class defining the operations to be used to notify this
object.
ConcreteObserverA, ConcreteObserver2 - concrete Observer implementations.
The flow is simple: the main framework instantiate the ConcreteObservable object. Then it
instantiate and attaches the concrete observers to it using the methods defined in the
Observable interface. Each time the state of the subject it's changing it notifies all the
attached Observers using the methods defined in the Observer interface. When a new
Observer is added to the application, all we need to do is to instantiate it in the main
framework and to add attach it to the Observable object. The classes already created will
remain unchanged.

Applicability & Examples
The observer pattern is used when:

the change of a state in one object must be reflected in another object without keeping the
objects tight coupled.
the framework we are writing needs to be enhanced in future with new observers with
minimal changes.
Some Classical Examples:
Model View Controller Pattern - The observer pattern is used in the model view
controller (MVC) architectural pattern. In MVC the this pattern is used to decouple the
model from the view. View represents the Observer and the model is
theObservable object.
Event management - This is one of the domains where the Observer patterns is
extensively used. Swing and .Net are extensively using the Observer pattern for
implementing the events mechanism.



Example - News Agency
Lets' take the example of a news agency.A news agency gather news news and publish
them to different subscribers. We need to create a framework for and agency to be able to
inform immediately, when event occurs, its subscribers about the event. The subscribers
can receive the news in different ways: Emails, SMS, ... The solution need to be extensively
enough to support new types of subscribers(maybe new communication technologies will
appear).


Obviously, the agency is represented by an Observable(Subject) class
named NewsPublisher. This one is created as an abstract class because the agency want
to create several types of Observable objects: in the beginning only for business news, but
after some time sport and political new will be published. The concrete class
is BusinessNewsPublisher.
The observer logic is implemented in NewsPublisher. It keeps a list of all it subscribers
and it informs them about the latest news. The subscribers are represented by some
observers (SMSSubscriber, EmailSubscriber). Both the observers mentioned above are
inherited from the Subscriber. The subscriber is the abstract class which is known to the
publisher. The publisher doesn't know about concrete observers, it knows only about their
abstraction.
In the main class a publisher(Observable) is built and a few subscribers(Observers). The
subscribers are subscribed to the publisher and they can be unsubscribed. In this
architecture new types of subscribers can be easily added(instant messaging, ...) and new
types of publishers(Weather News, Sport News, ...).
Specific Implementation Problems
Many subjects to Many observers
It's not a common situation but there are cases when a there are many observers that need
to observe more than one subject. In this case the observer need to be notified not only
about the change, but also which is the subject with the state changed. This can be realized
very simple by adding to the subjects reference in the update notification method. The
subject will pass a reference to itself(this) to the when notify the observer.
Who triggers the update?
The communication between the subject and its observers is done through the notify
method declared in observer interface. But who it cat be triggered from either subject or
observer object. Usually the notify method is triggered by the subject when it's state is
changed. But sometimes when the updates are frequent the consecutive changes in the
subject will determine many unnecessary refresh operations in the observer. In order to
make this process more efficient the observer can be made responsible for starting the
notify operation when it consider necessary.
Making sure Subject state is self-consistent before notification
The subject state should be consistent when the notify operation is triggered. If changes are
made in the subject state after the observer is notified, it will will be refreshed with an old
state. This seems hard to achieve but in practice this can be easily done when Subject
subclass operations call inherited operations. In the following example, the observer is
notified when the subject is in an inconsistent state:
class Observable{
...
int state = 0;
int additionalState = 0;
public updateState(int increment)
{
state = state + increment;
notifyObservers();
}
...
}

class ConcreteObservable extends Observable{
...
public updateState(int increment){
super.updateState(increment); // the observers are notified
additionalState = additionalState + increment; // the state is
changed after the notifiers are updated
}
...
}
This pitfall can be avoided using template methods in the abstract subject superclass for
calling the notify operations. Then subject subclass will implement the operations(s) of the
template:
class Observable{
...
int state = 0;
int additionalState = 0;
public void final updateState(int increment)
{
doUpdateState(increment);
notifyObservers();
}
public void doUpdateState(int increment)
{
state = state + increment;
}
...
}

class ConcreteObservable extends Observable{
...
public doUpdateState(int increment){
super.doUpdateState(increment); // the observers are notified
additionalState = additionalState + increment; // the state is
changed after the notifiers are updated
}
...
}
The Operations defined in the subject base class which triggers notify operation should be
documented.


Push and pull communication methods
There are 2 methods of passing the data from the subject to the observer when the state is
being changed in the subject side:

Push model - The subjects send detailed information about the change to the observer whether it uses
it or not. Because the subject needs to send the detailed information to the observer this might be
inefficient when a large amount of data needs to be sent and it is not used. Another aproach would be
to send only the information required by the observer. In this case the subject should be able to
distinguish between different types of observers and to know the required data of each of them,
meaning that the subject layer is more coupled to observer layer.
Pull model - The subject just notifies the observers when a change in his state appears and it's the
responsibility of each observer to pull the required data from the subject. This can be inefficient because
the communication is done in 2 steps and problems might appear in multithreading environments.

Specifying points of interests
The efficiency can be improved by specifying which are the events on which each observer
is interested. This can be realized by adding a new class defining an aspect. When an
observer is registering it will provide the aspects in which it is interested:
class Subject{
...
void attach(Observer observer, Aspect interest);
...
}

Encapsulating complex update semantics
When we have several subjects and observers the relations between them we'll become
more complex. First of all are have a many to many relation, more difficult to manage
directly. Second of all the relation between subjects and observers can contain some logic.
Maybe we want to have an observer notified only when all the subjects will change their
states. In this case we should introduce another object responsible (called ChangeManager)
for the following actions:
to maintain the many to many relations between the subjects and their observers.
to encapsulate the logic of notify the observers.
to receive the notifications from subjects and delegate them to the observers(based on the
logic it encapsulate)
Basically the Change Manager is an observer because if gets notified of the changes of the
subject and in the same time is an subject because it notify the observers. The
ChangeManager is an implemenation of the Mediator pattern.


The Observer pattern is usually used in combination with other design patterns:
Factory pattern - It's very likely to use the factory pattern to create the Observers so no
changes will be required even in the main framework. The new observers can be added
directly in the configuration files.
Template Method - The observer pattern can be used in conjunction with the Template
Method Pattern to make sure that Subject state is self-consistent before notification
Mediator Pattern - The mediator pattern can be used when we have cases of complex
cases of many subjects an many observers

Strategy
Motivation
There are common situations when classes differ only in their behavior. For this cases is a
good idea to isolate the algorithms in separate classes in order to have the ability to select
different algorithms at runtime.
Intent
Define a family of algorithms, encapsulate each one, and make them interchangeable.
Strategy lets the algorithm vary independently from clients that use it.
Implementation

Strategy - defines an interface common to all supported algorithms. Context uses this
interface to call the algorithm defined by a ConcreteStrategy.

ConcreteStrategy - each concrete strategy implements an algorithm.

Context
contains a reference to a strategy object.
may define an interface that lets strategy accessing its data.
The Context objects contains a reference to the ConcreteStrategy that should be used.
When an operation is required then the algorithm is run from the strategy object. The
Context is not aware of the strategy implementation. If necessary, addition objects can be
defined to pass data from context object to strategy.

The context object receives requests from the client and delegates them to the strategy
object. Usually the ConcreteStartegy is created by the client and passed to the context.
From this point the clients interacts only with the context.

Applicability & Examples
Example - Robots Application


Let's consider an application used to simulate and study robots interaction. For the
beginning a simple application is created to simulate an arena where robots are interacting.
We have the following classes:

IBehaviour (Strategy) - an interface that defines the behavior of a robot

Conctete Strategies: AggressiveBehaviour, DefensiveBehaviour, NormalBehaviour; each of
them defines a specific behavior. In order to decide the action this class needs information
that is passed from robot sensors like position, close obstacles, etc.

Robot - The robot is the context class. It keeps or gets context information such as position,
close obstacles, etc, and passes necessary information to the Strategy class.

In the main section of the application the several robots are created and several different
behaviors are created. Each robot has a different behavior assigned: 'Big Robot' is an
aggressive one and attacks any other robot found, 'George v.2.1' is really scared and run
away in the opposite direction when it encounter another robot and 'R2' is pretty calm and
ignore any other robot. At some point the behaviors are changed for each robot.
public interface IBehaviour {
public int moveCommand();
}

public class AgressiveBehaviour implements IBehaviour{
public int moveCommand()
{
System.out.println("\tAgressive Behaviour: if find another robot
attack it");
return 1;
}
}

public class DefensiveBehaviour implements IBehaviour{
public int moveCommand()
{
System.out.println("\tDefensive Behaviour: if find another robot
run from it");
return -1;
}
}

public class NormalBehaviour implements IBehaviour{
public int moveCommand()
{
System.out.println("\tNormal Behaviour: if find another robot
ignore it");
return 0;
}
}

public class Robot {
IBehaviour behaviour;
String name;

public Robot(String name)
{
this.name = name;
}

public void setBehaviour(IBehaviour behaviour)
{
this.behaviour = behaviour;
}

public IBehaviour getBehaviour()
{
return behaviour;
}

public void move()
{
System.out.println(this.name + ": Based on current position" +
"the behaviour object decide the next
move:");
int command = behaviour.moveCommand();
// ... send the command to mechanisms
System.out.println("\tThe result returned by behaviour object " +
"is sent to the movement mechanisms " +
" for the robot '" + this.name + "'");
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}


public class Main {

public static void main(String[] args) {

Robot r1 = new Robot("Big Robot");
Robot r2 = new Robot("George v.2.1");
Robot r3 = new Robot("R2");

r1.setBehaviour(new AgressiveBehaviour());
r2.setBehaviour(new DefensiveBehaviour());
r3.setBehaviour(new NormalBehaviour());

r1.move();
r2.move();
r3.move();

System.out.println("\r\nNew behaviours: " +
"\r\n\t'Big Robot' gets really scared" +
"\r\n\t, 'George v.2.1' becomes really mad because"
+
"it's always attacked by other robots" +
"\r\n\t and R2 keeps its calm\r\n");

r1.setBehaviour(new DefensiveBehaviour());
r2.setBehaviour(new AgressiveBehaviour());

r1.move();
r2.move();
r3.move();
}
}

Specific problems and implementation
Passing data to/from Strategy object
Usually each strategy need data from the context have to return some processed data to
the context. This can be achieved in 2 ways.
creating some additional classes to encapsulate the specific data.
passing the context object itself to the strategy objects. The strategy object can set
returning data directly in the context.
When data should be passed the drawbacks of each method should be analyzed. For
example, if some classes are created to encapsulate additional data, a special care should
be paid to what fields are included in the classes. Maybe in the current implementation all
required fields are added, but maybe in the future some new strategy concrete classes
require data from context which are not include in additional classes. Another fact should be
specified at this point: it's very likely that some of the strategy concrete classes will not use
field passed to the in the additional classes.

On the other side, if the context object is passed to the strategy then we have a tighter
coupling between strategy and context.
Families of related algorithms.
The strategies can be defined as a hierarchy of classes offering the ability to extend and
customize the existing algorithms from an application. At this point the composite design
pattern can be used with a special care.
Optionally Concrete Strategy Objects
It's possible to implement a context object that carries an implementation for default or a
basic algorithm. While running it, it checks if it contains a strategy object. If not it will run
the default code and that's it. If a strategy object is found, it is called instead (or in
addition) of the default code. This is an elegant solution to exposing some customization
points to be used only when they are required. Otherwise the clients don't have to deal with
Strategy objects.
Strategy and Creational Patterns
In the classic implementation of the pattern the client should be aware of the strategy
concrete classes. In order to decouple the client class from strategy classes is possible to
use a factory class inside the context object to create the strategy object to be used. By
doing so the client has only to send a parameter (like a string) to the context asking to use
a specific algorithm, being totally decoupled of strategy classes.
Strategy and Bridge
Both of the patterns have the same UML diagram. But they differ in their intent since the
strategy is related with the behavior and bridge is for structure. Further more, the coupling
between the context and strategies is tighter that the coupling between the abstraction and
implementation in the bring pattern.

Hot points
The strategy design pattern splits the behavior (there are many behaviors) of a class from
the class itself. This has some advantages, but the main draw back is that a client must
understand how the Strategies differ. Since clients get exposed to implementation issues
the strategy design pattern should be used only when the variation in behavior is relevant
to them.

Null Object Pattern
Motivation
There are some cases when a system has to use some functionality and some cases when it
doesn't. Let's say we have to implement a class that should send the results to a log file or
to the console. But this is just an additional option and the data is logged depending on the
configuration values.
If there are cases when the client module does not have to log any data then it has to check
the configuration parameter in and if block and then to call or not the Logger class. But as
we know the 'if' block is not an elegant solution.
Intent
Provide an object as a surrogate for the lack of an object of a given type.
The Null Object Pattern provides intelligent do nothing behavior, hiding the details from its
collaborators.



Implementation
The participants classes in this pattern are:

AbstractClass - defines abstract primitive operations that concrete implementations have
to define.
RealClass - a real implementation of the AbstractClass performing some real actions.
NullClass - a implementation which do nothing of the abstract class, in order to provide a
non-null object to the client.
Client - the client gets an implementation of the abstract class and uses it. It doesn't really
care if the implementation is a null object or an real object since both of them are used in
the same way.

Applicability & Examples
Example: Log System
Let's say we need a logging framework in order to support the logging of an application. The
framework must fulfill the following requirements:
The destination of the output messages should be selected from a configuration file and it
can be one of the following options: Log File, Standard Console or Log Disabled.
Must be open for extension; new logging mechanism can be added without touching the
existing code.
Specific problems and implementation
Null Object and Factory
The Null Object design pattern is more likely to be used in conjunction with the Factory
pattern. The reason for this is obvious: A Concrete Classes need to be instantiated and then
to be served to the client. The client uses the concrete class. The concrete class can be a
Real Object or a Null Object.
Null Object and Template Method
The Template method design pattern need to define an abstract class that define the
template and each concrete class implements the steps for the template. If there are cases
when sometimes template is called and sometimes not then, in order to avoid the checking
a Null Object can be use to implement a Concrete Template that does nothing.
Removing old functionality
The Null Object can be used to remove old functionality by replacing it with null objects. The
big advantage is that the existing code doesn't need to be touched.
Conclusion
The Null Object Pattern is used to avoid special if blocks for do nothing code, by putting the
do nothing code in the Null Object which becomes responsible for doing nothing. The client
is not aware anymore if the real object or the null object is called so the 'if' section is
removed from client implementation.


Structural Patterns
Adapter Pattern
Motivation
The adapter pattern is adapting between classes and objects. Like any adapter in the real
world it is used to be an interface, a bridge between two objects. In real world we have
adapters for power supplies, adapters for camera memory cards, and so on. Probably
everyone have seen some adapters for memory cards. If you can not plug in the camera
memory in your laptop you can use and adapter. You plug the camera memory in the
adapter and the adapter in to laptop slot. That's it, it's really simple.
What about software development? It's the same. Can you imagine an situation when you
have some class expecting some type of object and you have an object offering the same
features, but exposing a different interface? Of course, you want to use both of them so you
don't to implement again one of them, and you don't want to change existing classes, so
why not create an adapter...
Intent
Convert the interface of a class into another interface clients expect.
Adapter lets classes work together, that could not otherwise because of incompatible
interfaces.
Implementation
The figure below shows a UML class diagram for the Adapter Pattern:


The classes/objects participating in adapter pattern:

Target - defines the domain-specific interface that Client uses.
Adapter - adapts the interface Adaptee to the Target interface.
Adaptee - defines an existing interface that needs adapting.
Client - collaborates with objects conforming to the Target interface.

Applicability & Examples
The visitor pattern is used when:

When you have a class(Target) that invokes methods defined in an interface and you have a
another class(Adapter) that doesn't implement the interface but implements the operations
that should be invoked from the first class through the interface. You can change none of
the existing code. The adapter will implement the interface and will be the bridge between
the 2 classes.
When you write a class (Target) for a generic use relying on some general interfaces and
you have some implemented classes, not implementing the interface, that needs to be
invoked by the Target class.
Adapters are encountered everywhere. From real world adapters to software adapters
Non Software Examples of Adapter Patterns : Power Supply Adapters, card readers
and adapters, ...
Software Examples of Adapter Patterns: Wrappers used to adopt 3rd parties libraries
and frameworks - most of the applications using third party libraries use adapters as a
middle layer between the application and the 3rd party library to decouple the application
from the library. If another library has to be used only an adapter for the new library is
required without having to change the application code.

Specific problems and implementation
Objects Adapters - Based on Delegation
Objects Adapters are the classical example of the adapter pattern. It uses composition, the
Adaptee delegates the calls to Adaptee (opossed to class adapters which extends the
Adaptee). This behaviour gives us a few advantages over the class adapters(however the
class adapters can be implemented in languages allowing multiple inheritance). The main
advantage is that the Adapter adapts not only the Adpatee but all its subclasses. All it's
subclasses with one "small" restriction: all the subclasses which don't add new methods,
because the used mechanism is delegation. So for any new method the Adapter must be
changed or extended to expose the new methods as well. The main disadvantage is that it
requires to write all the code for delegating all the necessary requests tot the Adaptee.
Class Adapters - Based on (Multiple) Inheritance


Class adapters can be implemented in languages supporting multiple inheritance(Java, C#
or PHP does not support multiple inheritance). Thus, such adapters can not be easy
implemented in Java, C# or VB.NET. Class adapter uses inheritance instead of composition.
It means that instead of delegating the calls to the Adaptee, it subclasses it. In conclusion it
must subclass both the Target and the Adaptee. There are advantages and disadvantages:
It adapts the specific Adaptee class. The class it extends. If that one is subclassed it can not
be adapted by the existing adapter.
It doesn't require all the code required for delegation, which must be written for an Object
Adapter.
If the Target is represented by an interface instead of a class then we can talk about "class"
adapters, because we can implement as many interfaces as we want.
How Much the Adapter Should Do?
This question has a really simple response: it should do how much it has to in order to
adapt. It's very simple, if the Target and Adaptee are similar then the adapter has just to
delegate the requests from the Target to the Adaptee. If Target and Adaptee are not
similar, then the adapter might have to convert the data structures between those and to
implement the operations required by the Target but not implemented by the Adaptee.
Two-Ways Adapters
The Two-Ways Adapters are adapters that implements both interfaces of Target and
Adaptee. The adapted object can be used as Target in new systems dealing with Target
classes or as Adaptee in other systems dealing with Adaptee classes. Going further on this
line of thinking, we can have adapters implementing n interfaces, adapting to n systems.
Two-way adapters and n-way adapters are hard to implement in systems not supporting
multiple inheritance. If adapter has to extend the Target class it can not extent another
class like Adaptee, so the Adaptee should be an interface and all the calls should be
delegated from the adapter to the Adaptee object.
Adapter Pattern and Strategy Pattern
Adapter Pattern and Strategy Pattern - there are many cases when the adapter can play the
role of the Strategy Pattern. If we have several modules implementing the same
functionality and we wrote adapters for them, the adapters are implementing the same
interface. We can simply replace the adapters objects at run time because they implements
the same interface.

Bridge Pattern

Motivation
Sometimes an abstraction should have different implementations; consider an object that
handles persistence of objects over different platforms using either relational databases or
file system structures (files and folders). A simple implementation might choose to extend
the object itself to implement the functionality for both file system and RDBMS. However
this implementation would create a problem; Inheritance binds an implementation to the
abstraction and thus it would be difficult to modify, extend, and reuse abstraction and
implementation independently.
Intent
The intent of this pattern is to decouple abstraction from implementation so that the two
can vary independently.
Implementation
The figure below shows a UML class diagram for the Bridge Pattern:

The participants classes in the bridge pattern are:

Abstraction - Abstraction defines abstraction interface.
AbstractionImpl - Implements the abstraction interface using a reference to an object of
type Implementor.
Implementor - Implementor defines the interface for implementation classes. This
interface does not need to correspond directly to abstraction interface and can be very
different. Abstraction imp provides an implementation in terms of operations provided by
Implementor interface.
ConcreteImplementor1, ConcreteImplementor2 - Implements the Implementor
interface.
Description
An Abstraction can be implemented by an abstraction implementation, and this
implementation does not depend on any concrete implementers of the Implementor
interface. Extending the abstraction does not affect the Implementor. Also extending the
Implementor has no effect on the Abstraction.
Applicability & Examples
The bridge pattern applies when there is a need to avoid permanent binding between an
abstraction and an implementation and when the abstraction and implementation need to
vary independently. Using the bridge pattern would leave the client code unchanged with no
need to recompile the code.
Example - Object Persistence API Example
As discussed previously a persistence API can have many implementations depending on
the presence or absence of a relational database, a file system, as well as on the underlying
operating system.

Source: Click here to see java source code


Specific problems and implementation
Graphical User Interface Frameworks
Graphical User Interface Frameworks use the bridge pattern to separate abstractions from
platform specific implementation. For example GUI frameworks separate a Window
abstraction from a Window implementation for Linux or Mac OS using the bridge pattern.
Related Patterns
Abstract Factory Pattern - An Abstract Factory pattern can be used create and configure
a particular Bridge, for example a factory can choose the suitable concrete implementor at
runtime.
Consequences
Known Uses:
Decoupling interface and implementation. An implementation is not bound permanently to
an interface. The implementation of an abstraction can be configured and even switched at
run-time.
Abstraction and Implementor hierarchies can be extended independently.
Known Uses:
GUI frameworks as discussed previously.
Persistence Frameworks as discussed previously.

Composite Pattern

Motivation
There are times when a program needs to manipulate a tree data structure and it is
necessary to treat both Branches as well as Leaf Nodes uniformly. Consider for example a
program that manipulates a file system. A file system is a tree structure that contains
Branches which are Folders as well as Leaf nodes which are Files. Note that a folder object
usually contains one or more file or folder objects and thus is a complex object where a file
is a simple object. Note also that since files and folders have many operations and attributes
in common, such as moving and copying a file or a folder, listing file or folder attributes
such as file name and size, it would be easier and more convenient to treat both file and
folder objects uniformly by defining a File System Resource Interface.
Intent
The intent of this pattern is to compose objects into tree structures to represent part-whole
hierarchies.
Composite lets clients treat individual objects and compositions of objects uniformly.
Implementation
The figure below shows a UML class diagram for the Composite Pattern:



Component - Component is the abstraction for leafs and composites. It defines the
interface that must be implemented by the objects in the composition. For example a file
system resource defines move, copy, rename, and getSize methods for files and folders.
Leaf - Leafs are objects that have no children. They implement services described by the
Component interface. For example a file object implements move, copy, rename, as well as
getSize methods which are related to the Component interface.
Composite - A Composite stores child components in addition to implementing methods
defined by the component interface. Composites implement methods defined in the
Component interface by delegating to child components. In addition composites provide
additional methods for adding, removing, as well as getting components.
Client - The client manipulates objects in the hierarchy using the component interface.
A client has a reference to a tree data structure and needs to perform operations on all
nodes independent of the fact that a node might be a branch or a leaf. The client simply
obtains reference to the required node using the component interface, and deals with the
node using this interface; it doesnt matter if the node is a composite or a leaf.

Applicability & Examples
The composite pattern applies when there is a part-whole hierarchy of objects and a client
needs to deal with objects uniformly regardless of the fact that an object might be a leaf or
a branch.

Example - Graphics Drawing Editor.
In graphics editors a shape can be basic or complex. An example of a simple shape is a line,
where a complex shape is a rectangle which is made of four line objects. Since shapes have
many operations in common such as rendering the shape to screen, and since shapes follow
a part-whole hierarchy, composite pattern can be used to enable the program to deal with
all shapes uniformly.
In the example we can see the following actors:

Shape (Component) - Shape is the abstraction for Lines, Rectangles (leafs) and and
ComplexShapes (composites).
Line, Rectangle (Leafs) - objects that have no children. They implement services
described by the Shape interface.
ComplexShape (Composite) - A Composite stores child Shapes in addition to
implementing methods defined by the Shape interface.
GraphicsEditor (Client) - The GraphicsEditor manipulates Shapes in the hierarchy.
Alternative Implementation: Note that in the previous example there were times when
we have avoided dealing with composite objects through the Shape interface and we have
specifically dealt with them as composites (when using the method addToShape()). To avoid
such situations and to further increase uniformity one can add methods to add, remove, as
well as get child components to the Shape interface. The UML diagram below shows it:

Source: Click here to see java source code
Specific problems and implementation
Graphics Editors use composite pattern to implement complex and simple graphics as
previously explained.
File System implementations use the composite design pattern as described previously.

Consequences
The composite pattern defines class hierarchies consisting of primitive objects and
composite objects. Primitive objects can be composed into more complex objects, which in
turn can be composed.
Clients treat primitive and composite objects uniformly through a component interface
which makes client code simple.
Adding new components can be easy and client code does not need to be changed since
client deals with the new components through the component interface.

Related Patterns
Decorator Pattern - Decorator is often used with Composite. When decorators and
composites are used together, they will usually have a common parent class. So decorators
will have to support the Component interface with operations like Add, Remove, and
GetChild.
Known Uses
File System Implementation as discussed previously.
Graphics Editors as discussed previously.

Decorator Pattern

Motivation
Extending an objects functionality can be done statically (at compile time) by using
inheritance however it might be necessary to extend an objects functionality dynamically
(at runtime) as an object is used.
Consider the typical example of a graphical window. To extend the functionality of the
graphical window for example by adding a frame to the window, would require extending
the window class to create a FramedWindow class. To create a framed window it is
necessary to create an object of the FramedWindow class. However it would be impossible
to start with a plain window and to extend its functionality at runtime to become a framed
window.

Intent
The intent of this pattern is to add additional responsibilities dynamically to an object.
Implementation
The figure below shows a UML class diagram for the Decorator Pattern:
The participants classes in the decorator pattern are:

Component - Interface for objects that can have responsibilities added to them
dynamically.
ConcreteComponent - Defines an object to which additional responsibilities can be added.
Decorator - Maintains a reference to a Component object and defines an interface that
conforms to Component's interface.
Concrete Decorators - Concrete Decorators extend the functionality of the component by
adding state or adding behavior.
Description
The decorator pattern applies when there is a need to dynamically add as well as remove
responsibilities to a class, and when subclassing would be impossible due to the large
number of subclasses that could result.
Applicability & Examples
Example - Extending capabilities of a Graphical Window at runtime

Source: Click here to see java source code
In Graphical User Interface toolkits windows behaviors can be added dynamically by using
the decorator design pattern.
Specific problems and implementation
Graphical User Interface Frameworks
GUI toolkits use decoration pattern to add functionalities dynamically as explained before.
Related Patterns
Adapter Pattern - A decorator is different from an adapter in that a decorator changes
object's responsibilities, while an adapter changes an object interface.
Composite Pattern - A decorator can be viewed as a degenerate composite with only one
component. However, a decorator adds additional responsibilities.
Consequences
Decoration is more convenient for adding functionalities to objects instead of entire classes
at runtime. With decoration it is also possible to remove the added functionalities
dynamically.
Decoration adds functionality to objects at runtime which would make debugging system
functionality harder.


Known Uses:
GUI toolkits as has been previously explained.

Flyweight Pattern
Motivation
Some programs require a large number of objects that have some shared state among
them. Consider for example a game of war, were there is a large number of soldier objects;
a soldier object maintain the graphical representation of a soldier, soldier behavior such as
motion, and firing weapons, in addition soldiers health and location on the war terrain.
Creating a large number of soldier objects is a necessity however it would incur a huge
memory cost. Note that although the representation and behavior of a soldier is the same
their health and location can vary greatly.

Intent
The intent of this pattern is to use sharing to support a large number of objects that have
part of their internal state in common where the other part of state can vary.


Implementation
The figure below shows a UML class diagram for the Flyweight Pattern:


Flyweight - Declares an interface through which flyweights can receive and act on extrinsic
state.
ConcreteFlyweight - Implements the Flyweight interface and stores intrinsic state. A
ConcreteFlyweight object must be sharable. The Concrete flyweight object must maintain
state that it is intrinsic to it, and must be able to manipulate state that is extrinsic. In the
war game example graphical representation is an intrinsic state, where location and health
states are extrinsic. Soldier moves, the motion behavior manipulates the external state
(location) to create a new location.
FlyweightFactory - The factory creates and manages flyweight objects. In addition the
factory ensures sharing of the flyweight objects. The factory maintains a pool of different
flyweight objects and returns an object from the pool if it is already created, adds one to the
pool and returns it in case it is new.
In the war example a Soldier Flyweight factory can create two types of flyweights : a Soldier
flyweight, as well as a Colonel Flyweight. When the Client asks the Factory for a soldier, the
factory checks to see if there is a soldier in the pool, if there is, it is returned to the client, if
there is no soldier in pool, a soldier is created, added to pool, and returned to the client, the
next time a client asks for a soldier, the soldier created previously is returned, no new
soldier is created.
Client - A client maintains references to flyweights in addition to computing and
maintaining extrinsic state
A client needs a flyweight object; it calls the factory to get the flyweight object. The factory
checks a pool of flyweights to determine if a flyweight object of the requested type is in the
pool, if there is, the reference to that object is returned. If there is no object of the required
type, the factory creates a flyweight of the requested type, adds it to the pool, and returns
a reference to the flyweight. The flyweight maintains intrinsic state (state that is shared
among the large number of objects that we have created the flyweight for) and provides
methods to manipulate external state (State that vary from object to object and is not
common among the objects we have created the flyweight for).


Applicability & Examples
The flyweight pattern applies to a program using a huge number of objects that have part of
their internal state in common where the other part of state can vary. The pattern is used
when the larger part of the objects state can be made extrinsic (external to that object).



Example - The war game.
The war game instantiates 5 Soldier clients, each client maintains its internal state which is
extrinsic to the soldier flyweight. And Although 5 clients have been instantiated only one
flyweight Soldier has been used.

Source: Click here to see java source code


Specific problems and implementation


Text Editors
Object oriented text editors need to create Character Objects to represent each character
that is in the document. A Character object maintains information about what is the
character, what is its font, what is the size of the character, as well as character location
inside the document. A document typically consists of extremely large number of character
objects which requires large memory. Note that the number of characters in general (Digits,
Letters, Other special characters) is known and is fixed, and the fonts that can be applied to
each character are also known, thus by creating a Letter flyweight that maintains Character
Type (letter, digit, etc), as well as font, and by creating a Letter Client object that only
maintains each characters location inside the document, we have reduced the editors
memory requirements drastically.


Consequences
Flyweight pattern saves memory by sharing flyweight objects among clients. The amount of
memory saved generally depends on the number of flyweight categories saved (for example
a soldier category and a lieutenant category as discussed earlier).


Related Patterns
Factory and Singleton patterns - Flyweights are usually created using a factory and the
singleton is applied to that factory so that for each type or category of flyweights a single
instance is returned.
State and Strategy Patterns - State and Strategy objects are usually implemented as
Flyweights.


Known Uses
Games with graphics as discussed with the War Game Example
Text Editors as discussed in the Text Editors example.

Proxy Pattern


Motivation
Sometimes we need the ability to control the access to an object. For example if we need to
use only a few methods of some costly objects we'll initialize those objects when we need
them entirely. Until that point we can use some light objects exposing the same interface as
the heavy objects. These light objects are called proxies and they will instantiate those
heavy objects when they are really need and by then we'll use some light objects instead.
This ability to control the access to an object can be required for a variety of reasons:
controlling when a costly object needs to be instantiated and initialized, giving different
access rights to an object, as well as providing a sophisticated means of accessing and
referencing objects running in other processes, on other machines.
Consider for example an image viewer program. An image viewer program must be able to
list and display high resolution photo objects that are in a folder, but how often do someone
open a folder and view all the images inside. Sometimes you will be looking for a particular
photo, sometimes you will only want to see an image name. The image viewer must be able
to list all photo objects, but the photo objects must not be loaded into memory until they
are required to be rendered.


Intent
The intent of this pattern is to provide a Placeholder for an object to control references
to it.


Implementation
The figure below shows a UML class diagram for the Proxy Pattern:

The participants classes in the proxy pattern are:

Subject - Interface implemented by the RealSubject and representing its services. The
interface must be implemented by the proxy as well so that the proxy can be used in any
location where the RealSubject can be used.
Proxy
o Maintains a reference that allows the Proxy to access the RealSubject.
o Implements the same interface implemented by the RealSubject so that the Proxy can be
substituted for the RealSubject.
o Controls access to the RealSubject and may be responsible for its creation and deletion.
o Other responsibilities depend on the kind of proxy.
RealSubject - the real object that the proxy represents.
Description
A client obtains a reference to a Proxy, the client then handles the proxy in the same way it
handles RealSubject and thus invoking the method doSomething(). At that point the proxy
can do different things prior to invoking RealSubjects doSomething() method. The client
might create a RealSubject object at that point, perform initialization, check permissions of
the client to invoke the method, and then invoke the method on the object. The client can
also do additional tasks after invoking the doSomething() method, such as incrementing the
number of references to the object.


Applicability & Examples
The Proxy design pattern is applicable when there is a need to control access to an Object,
as well as when there is a need for a sophisticated reference to an Object. Common
Situations where the proxy pattern is applicable are:

Virtual Proxies: delaying the creation and initialization of expensive objects until needed,
where the objects are created on demand (For example creating the RealSubject object only
when the doSomething method is invoked).
Remote Proxies: providing a local representation for an object that is in a different
address space. A common example is Java RMI stub objects. The stub object acts as a
proxy where invoking methods on the stub would cause the stub to communicate and
invoke methods on a remote object (called skeleton) found on a different machine.
Protection Proxies: where a proxy controls access to RealSubject methods, by giving
access to some objects while denying access to others.
Smart References: providing a sophisticated access to certain objects such as tracking the
number of references to an object and denying access if a certain number is reached, as
well as loading an object from database into memory on demand.



Example - Virtual Proxy Example.
Consider an image viewer program that lists and displays high resolution photos. The
program has to show a list of all photos however it does not need to display the actual
photo until the user selects an image item from a list.

The code below shows the Image interface representing the Subject. The interface has a
single method showImage() that the Concrete Images must implement to render an image
to screen.
package proxy;

/**
* Subject Interface
*/
public interface Image {

public void showImage();

}


The code below shows the Proxy implementation, the image proxy is a virtual proxy that
creates and loads the actual image object on demand, thus saving the cost of loading an
image into memory until it needs to be rendered:
package proxy;

/**
* Proxy
*/
public class ImageProxy implements Image {

/**
* Private Proxy data
*/
private String imageFilePath;

/**
* Reference to RealSubject
*/
private Image proxifiedImage;


public ImageProxy(String imageFilePath) {
this.imageFilePath= imageFilePath;
}

@Override
public void showImage() {

// create the Image Object only when the image is required to
be shown

proxifiedImage = new HighResolutionImage(imageFilePath);

// now call showImage on realSubject
proxifiedImage.showImage();

}

}


The code below displays the RealSubject Implementation, which is the concrete and
heavyweight implementation of the image interface. The High resolution image, loads a high
resolution image from disk, and renders it to screen when showImage() is called.
package proxy;

/**
* RealSubject
*/
public class HighResolutionImage implements Image {

public HighResolutionImage(String imageFilePath) {

loadImage(imageFilePath);
}

private void loadImage(String imageFilePath) {

// load Image from disk into memory
// this is heavy and costly operation
}

@Override
public void showImage() {

// Actual Image rendering logic

}

}


The code below illustrates a sample image viewer program; the program simply loads three
images, and renders only one image, once using the proxy pattern, and another time
directly. Note that when using the proxy pattern, although three images have been loaded,
the High resolution image is not loaded into memory until it needs to be rendered, while in
the part not using the proxy, the three images are loaded into memory although one of
them is actually rendered.
package proxy;

/**
* Image Viewer program
*/
public class ImageViewer {


public static void main(String[] args) {

// assuming that the user selects a folder that has 3 images
//create the 3 images
Image highResolutionImage1 = new
ImageProxy("sample/veryHighResPhoto1.jpeg");
Image highResolutionImage2 = new
ImageProxy("sample/veryHighResPhoto2.jpeg");
Image highResolutionImage3 = new
ImageProxy("sample/veryHighResPhoto3.jpeg");

// assume that the user clicks on Image one item in a list
// this would cause the program to call showImage() for that image only
// note that in this case only image one was loaded into memory
highResolutionImage1.showImage();

// consider using the high resolution image object directly
Image highResolutionImageNoProxy1 = new
HighResolutionImage("sample/veryHighResPhoto1.jpeg");
Image highResolutionImageNoProxy2 = new
HighResolutionImage("sample/veryHighResPhoto2.jpeg");
Image highResolutionImageBoProxy3 = new
HighResolutionImage("sample/veryHighResPhoto3.jpeg");


// assume that the user selects image two item from images list
highResolutionImageNoProxy2.showImage();

// note that in this case all images have been loaded into memory
// and not all have been actually displayed
// this is a waste of memory resources

}

}



Specific problems and implementation


Java Remote Method Invocation (RMI)
In java RMI an object on one machine (executing in one JVM) called a client can invoke
methods on an object in another machine (another JVM) the second object is called a
remote object. The proxy (also called a stub) resides on the client machine and the client
invokes the proxy in as if it is invoking the object itself (remember that the proxy
implements the same interface that RealSubject implements). The proxy itself will handle
communication to the remote object, invoke the method on that remote object, and would
return the result if any to the client. The proxy in this case is a Remote proxy.


Related Patterns
Adapter Design Pattern - The adapter implements a different interface to the object it
adapts where a proxy implements the same interface as its subject.
Decorator Design Pattern - A decorator implementation can be the same as the proxy
however a decorator adds responsibilities to an object while a proxy controls access to it.


Consequences
Known Uses:
Java RMI as has been explained implements a remote proxy
Security Proxies that controls access to objects can be found in many object oriented
languages including java, C#, C++.

Você também pode gostar