Creational Pattern
Factory Method Pattern
Case Study Requirements
I have electronic show room I sell Samsung machines and Refrigerators.
I need an application that can show details of all my Samsung machines whenever I want.
Naive Implementation Proposal
Limitations in above approach
- Client is directly dealing with actual implementation that means client is tightly coupled so if any product name is changed we need to change the calling method name.
In our example we are accessing productDetails.getSamsungWashingMachineDetails()
In future if you want to get other product details you need to call some other method like productDetails.getSamsungRefrigeratorDetails which is huge change at client side.
- Different methods returning different types of objects so cannot provide a generic way to handle objects at client side.
- ProductDetails class size will be increased if new product is introduced that effects the readability of the class.
Definition
Factory Pattern defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Overview
Every Framework supports their services to developers with the help of set of abstract classes and Interfaces. These abstract classes are being implemented by the developers. But in beforehand framework designer do not have idea that how these objects are going to be created by Framework users. Handling these kinds of objects is really difficult to the Framework designer. This kind problem can be solved with the help of Factory Method design pattern.
Structure
Code Example
Benefits and Liabilities
- Client is not directly dealing with actual implementations so it is loosely coupled with actual implementation. Since all products are expected to be implemented ProductDeatils, if product is changed no huge change will be at client side.
- Since all products are implementing all products will have same so developer can provide a generic way to handle objects at client side.
- Adding new product is easy. Just implementing the interface ProductDeatils is enough
- Factory method provides the facility to subclass to implement how they want.
Points to Remember
You can also apply generics for bounded parameters. But it has its own limitations. If your application is “Ok” with those you can use as shown below
protected <T extends ProductDetails> T getProductFactory(Class<T> clazz) {
T samsungWS = null;
try {
samsungWS = clazz.newInstance();
samsungWS.setModelNo("Samsung washing machine model WWBW001");
samsungWS.setCapacity("6 kg");
samsungWS.setPrice("20000");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return samsungWS;
}
When to use
- When the implementation details are not known at development time i.e., Concrete implementation is being provided by others who will use our class in future.
- When a super class wants specify the object that are going to be created by subclass
- Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate
Example from Java API
Abstract Factory Pattern
Case Study Requirements
I have electronic show room I sell Samsung and LG washing machines and Refrigerators.
I need an interface where I can see details of all my Samsung or my LG machines whenever I need.
Naive Implementation Proposal
Naive Code Example
Output
Limitations in above approach
- Client is directly dealing with actual implementation that means Client is tightly coupled due to that if any product name is changed we need to change the calling method name.
In our example we are accessing productDetails.getSamsungRefrigeratorDetails () or productDetails.getSamsungWashingMachineDetails()
In future if you want to get other company product details you need to call some other methods that cause huge change at client side.
- ProductDetails class size will be increased if new product is introduced that effects the readability of the class.
Definition
Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
Structure
Code Example
Benefits and Liabilities
- It promotes loosely coupling and consistency among products.
- Adding new family of products is easy
- Factory method provides the facility to subclass to implement how they want.
But It has below Liabilities
- But Supporting new kinds of products will introduces new class hierarchy and this can be solved with the help of prototype pattern
- If clients need to perform subclass-specific operations, they won't be accessible through the abstract interface.
Points to Remember
- Abstract Factory pattern is the Factory pattern on factories. And deals with families of objects.
- Recommended Develop all Factories as Singleton. [Will be discussed in depth while discussing Singleton design pattern]
- Also recommended to define extensible factories
When to use
- When you want to make your system independent of how its products are created, composed and represented.
- A system should be configured with one of multiple families of products.
- When you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.
Example from Java API
javax.xml.parsers.DocumentBuilderFactory#newInstance()Za
Builder Design Pattern
Definition
Builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations.
Case Study Requirements
Simulate the preparation of a Burger which has below three phases
- Prepare Breads for Bottom and top
- Prepare stuff to keep inside
- Pack the Burger by keeping stuff in between 2 breads prepared.
Naive Implementation Proposal
Naive Code Example
Output
Bottom and Top breads Prepared with size 6 inches
Placed Mutton and other stuff on the bottom bread.
Closed Burger with top bread.
Limitations in above approach
- Here also Client is directly involving in the creation of Object
- If the Object is more complex It will be extra burden to Client to create the very big complex Object
- As way of creation is not separated from client, If other application can to use it
Structure
Code Example
Benefits and Liabilities
- It hides the way of creation of Object that is not necessary to know by Client
- Object Creation logic is completely separated from client.
- Object creation logic is divided into steps so that readability will be increased.
- More than one director can use same Builder to build Product variants from the same set of parts.
Points to Remember
- It is also called director, builder design patter
- getResult() should define in ConcreatBuilder.
When to use
If Creation of object is complex and involves more than one step and outcome of each step is an independent part of the object then this pattern is advised to use.
Example from Java API
java.lang.StringBuilder#append()
java.lang.StringBuffer#append()
Prototype Pattern
Definition
Prototype Pattern specifies the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype..
Structure
Code Example
Benefits and Liabilities
- Rather than creating object from scratch, taking copy of already existing object and modifying or customizing that will save the time and resources.
- Adding and removing prototypes at runtime is easy.
Points to Remember
- If prototypes are huge and not fixed in number, remember to track yourself by registering them. This registry is called Prototype Manager.
- Your prototype should support all operations that are required to enhance. Like increaseSize() in our Burger
- Consider deep and shallow clone If you use Object.clone()
When to use
- Use the Prototype pattern when a system should be independent of how its products are created, composed, and represented.
- Use this pattern whenever you are working with very complex object and you may need more than one object.
Example from Java API
Java.lang.Object#clone()
Singleton Design
Definition
Ensure a class only has one instance, and provide a global point of access to it.
Overview
To explain this I am taking the example of SessionFactory class in Hibernate. SessionFacoty manages the sessions create in entire application. SessionFactory instance is crated with configurations defined in Hibernate configure files. Creation of SessionFacotry instance is more expensive. It is advised that creation of SessionFactory only once is enough. Same in case of java.lang.Runtime also.
Singlet provides a smart way to maintain at most one object of the class.
It is recommended to create singletons Factory classes, Builder classes.
Then when to go for Static classes and when to go for singleton.
Static classes are recommended when we are not maintaining any state and not required any runtime features like dynamic method dispatch. These are preferred for utility methods
Singletons are preferred when it is maintaining states, configuration details your Projects and so on.
http://www.javaworld.com/article/2074897/java-web-development/when-is-a-singleton-not-a-singleton-.html
Structure
Code Example
Benefits and Liabilities
- As Singleton encapsulate itself, It will have the control on how client access it.
- Rather than using singleton you can go for static methods but in future if you want to use more than one but limited no of Objects then it will be difficult to change the class if you go for static approach. Same will be easy with Singletons.
Points to Remember
- Do not forget to declare private constructor
- Do not forget to have global & single entry point to your Class
- Make sure of thread-safety
if(fileUtility == null )
synchronized (FileUtility.class) {
fileUtility = new FileUtility() ;
}
return fileUtility ;
When to use
When you want use single object in the complete application and you don’t want allow to create more than one object you can choose it
Example from Java API
Java.lang.Runtime
Structural Pattern
Adapter Pattern
Definition
Adapter Pattern converts the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Overview
What is an Adapter in general? It converts or, to be more accurate, it adapts incompatible to things to compatible. For example take AC to DC adapters and DC to AC adapters.
All classes are supposed to be designed in such a way that they fulfill all kinds of requirements. For example when we take a class java.lang.String and it is designed in such way that it provides all string manipulating methods that can be done with a string. It is called cohesiveness. Dictionary meaning of cohesive is that “The state of cohering or sticking together” means all string related methods identified developed and placed or packed in String class itself. This String can be used in our domain specific projects. For example I want to develop an application that displays characters follows from top to down on the screen. This functionality is not available in String class. So this kind of domain specific functionalities can be implemented in our class and operations defined in String class can be used by composing this Sting into that Domain specific class. This domain specific class is called as adaptor whereas String is called Adoptee. Here Adaptor adopts String class to full fill our character fall requirements. Notice that we are not just adapting the String but also adding new future in Adapter class. And Adapter class is supposed to implement an interface and that is called Target. Client directly interacts with Target class. Target is implemented by Adaptor. Adaptor is being composed /extended by Adaptee.
Adapter pattern is used to adapt more than one incompatible class and makes them work together.
Clients call operations on an Adapter instance. In turn, the adapter calls Adaptee operations that carry out the request.
Case Study Requirements
Design an application that returns no of lines in a file given
Structure
Adapter classes can be implemented in 2 ways
- Class Adapter
- Object Adapter
Class Adapter
Object Adapter
Code Example – Object Adapet
Design an application that returns no of lines in a file given
Benefits and Liabilities
Class Adopter
- You are able to adapt a class to domain specific class easily by extending it. one limitation in this class adapter is that the subclasses of adaptee cannot be adapted.
Object Adopter
- You are able to adapt subclasses also as you are simple composing the adaptee object into adapter. So that you can also assign its subclass easily so a single Adapter work with many Adaptees.
Below are different types of adapters
- Pluggable Adapter
Here reflection API is used to call adaptee method and invokes it indirectly in the adapter.
Points to Remember
- While implementing the class use interfaces (p2i) not classes
- Internally Adpater uses Factory pattern if you have more than one adaptor
- Adapter pattern is closer to Decorator Pattern main difference is Decorator patter has nester composition.
When to use
- Whenever we need to adapt exiting class to domain specific functionality.
- When you want to use a class that related to other System.
- If more than one existing class needs to be enhanced (Object adapters)
- When our requirement is implementing a bridge between two systems, you can apply adapter pattern.
Example from Java API
java.io.InputStreamReader(InputStream) (returns a Reader)
Target is Reader interface
Adapter is InputStreamReader
Adaptee is InputStream
Composite Pattern
Definition
Composite Pattern composes objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Overview
Compose small components and group them into a single large component. These large components can be regrouped again to form even larger component. This composite pattern can be compared with tree structure. Tree has Branches and Branches has leaves. As per composite pattern Tree, Branch, Leave is required to implement same interface.
All leaves in the tree are called primitive objects and remaining objects are called Containers. If the recipient is a Leaf, then the request is handled directly. If the recipient is a Composite, then it forwards requests to its child components, possibly performing additional operations before and/or after forwarding.
Case Study Requirements
I am a Contractor. Recently I won a very big contract from Housing Board Colony of AP. I am responsible for constructing Housing Board colonies for Government employees. In this regard I need a software application that calculates total amount required to construct various types of colonies
Each colony is collection of houses each house is collection of rooms.
When I provide no of rooms, no of houses and no of colonies and price of each brick I should know the total cost for my Input.
Every Colony additional cost is 100000
Every House additional cost apart from 80000 apart from bricks cost.
Every room additional cost apart from 50000 apart from bricks cost.
Naïve Implementation Proposal
Naïve Code Example
Limitations in above approach
- If new room type is added for example “Drawing room” we need to change complete logic.
- No scope for reusability.
- No of variables in a class will be increased so that readability will be reduced.
- Adding new feature or changing existing feature is difficult. Like If I get new room type I need to change business logic
Structure
Code Example
Benefits and Liabilities
- Client need not to know if he is dealing with primitive or compound objects
- Easy to add new kinds of components
- Leaf nodes are forced to be implemented few method unnecessarily
Points to Remember
There are many issues to consider when implementing the Composite pattern:
- Explained Add and remove method should have the argument of type component
- Use Generic type collections that in composite class so that class casting problem can be avoided.
- Operation () should be implemented in composite in such way that it iterates all its child’s operation() method.
- Better to maintain references of child’s in Parent so that traversing will be easier. Even you can maintain parent reference. But it may consume some additional memory.
- Add(), remove () implementation is optional for leaf classes.
- Leaf classes can use the default implementation for add() and remove() whereas composite classes can override to returns its children. And it is advised to throw exception when add/removed failed and optionally use the same for default implementation.
When to use
- Whenever you have a primitive object and will be used to cumulatively to construct a bigger Object as explained above example.
Example from Java API
Java.awt.Container.add( java.awt.Component) component is a leaf node and container is a compound node. All AWT and swing component classes are sub classes of java.awt.Component)
Decorator Pattern
Definition
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality.
Overview
Every class has its own purpose and responsibility To add additional responsibilities we have different ways like extending from other class or implementing existing interface. For example I have an applet and I want to make it as Thread also. To do this you can implement Runnable interface but all these are class level. Moreover these are static. We cannot change them runtime. Solution for this is Decorator Pattern.
Decorator is used to decorate objects with other objects.
For example I have a 100 cc Engine and this engine is decorated with Passion Plus Body then it becomes Honda Passion Plus and the same engine is decorated with Splendor plus Body then it becomes splendor Plus
100cc Engine + decorated with Passion plus body = Hero Passion Plus
100cc Engine + decorated with Passion plus body + decorated with self-start = Hero Passion Pro.
Here Passion plus body and self-starters or decorators
Structure
Code Example
Benefits and Liabilities
- As discussed it is dynamic unlike extends and implements. But you might be end up with lots of objects with very few additional responsibilities as decorators.
- Since all are extended from same super class It is really difficult to debug
Points to Remember
- Remember actual component is subclass/interface of your core interface and decorators follows separate hierarchy. But both component and decorators comes from same common super interface.
- Don’t more stuff in decorators else debug will be more difficult.
- An alternative for this pattern is Strategy pattern. In Decorator patter you add behavior just by adding the decorator You can also achieve the same from doing the scratch. That will be explained in Strategy Pattern and It is advised to choose Strategies when component is heavyweight. We will discuss more about this while discussing strategy pattern
Example from Java API
Java IO package
BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(..));
Flyweight Pattern
Definition
Use sharing to support large numbers of fine-grained objects efficiently.
Overview
Bottom line of this pattern is share the memory for all similar type of Objects.
Flyweight Pattern is one of the powerful design patterns that can be applied when we have large no of objects. Before we learn about Flyweight we should know below two states of it.
1. Intrinsic and
2. Extrinsic
Intrinsic consist of information that is sharable and independent of Flyweight context but stored in Flyweight context whereas Extrinsic state depends on and varies with the flyweight and cannot be shared means Extrinsic state is calculated. Intrinsic data makes the object unique and extrinsic data passes as an argument.
The Flyweight pattern is often combined with the Composite pattern to represent a hierarchical structure as a graph with shared leaf nodes. A consequence of sharing is that flyweight leaf nodes cannot store a pointer to their parent. Rather, the parent pointer is passed to the flyweight as part of its extrinsic state. This has a major impact on how the objects in the hierarchy communicate with each other.
Most popular usage of Flyweight is java.lang.String.intern(). String is an immutable object and JVM maintains a pool and places it when you create Object for first time. That pooled objects will be shared from next time on words.
Structure
Code Example
Benefits and Liabilities
Memory is saved and the storage saving is proportional to the no of flyweights that are shared.
Points to Remember
- Remember to perform Garbage collection if the language is not supporting by default.
- It is highly recommended to use immutable object as Flyweights to avoid side effects of threads. If the content of two flyweight object is same, you can consider both are equal.
- Garbage collection is not required if number of Flyweights are small and limited.
When to use
- When the application uses a large number of objects and the application doesn't depend on object identity.
- When extrinsic state can be calculated and intrinsic can be stored.
- All subclasses of Flyweight are need not to shared.
- When the application has different objects and their behavior/properties are limited and each behavior/property is used by more than one object.
Example from Java API
- Boolean, Shot, Long, String.intern ()
public String intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
Façade (fu’ssad) Pattern
Definition
Provide a unified interface to a set of interfaces in a subsystem. Facade defines
a higher-level interface that makes the subsystem easier to use.
Overview
Dictionary meaning of Façade is “Face or front of a building”. It is highly advised to minimize the communication and dependency among the sub system. If the way of communication among components is clumsy, Adding new component or deleting existing one will be more difficult. Regularizing the communication process can be done with help this design pattern. To regularize the system Facde pattern advises us to have single entry point to our entire system. So that you can implement security systems authentication and authorization checks at entry point.
Structure
Code Example
\
Benefits and Liabilities
- It promotes loose coupling between the subsystem and its clients.
- It avoids the clumsiness among subsystems and if any feature is required to be changed or need to be added new features while communicating subsystem it will be a big deal if we don’t use Façade pattern
- Facade can also simplify porting systems to other platforms.
- Sub system can be changed easily as there is loosely coupling between client and subsystem
Points to Remember
- Make sure that single entry point entry is maintained to your subsystem.
- You can have multiple nested facades means make your application multiple subsystems and use a faced for each subsystem and use master faced to maintain all facades of you all subsystems.
When to use
- When there are many dependencies between clients and the implementation classes Use this façade pattern and decouple the subsystem from clients and other subsystems
Behavioral Pattern
Chain of Responsibilities
Definition
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
Overview
This chain of responsibility is very popular design patter can be observed it in many web projects.
First we will use one real time example. I want to have Ghee and my input is Milk. It contains below phases
Cow Milk → Boil milk → Get the Butter → Get the Ghee
^ ^ ^
| \ Take readymade Butter
Goat Milk \
Mix Water to get milk
\
Milk Powder
When we use this kind of approach our application will become loosely coupled, and independent of each other. We can add or remove or modify phases easily without touching other code. In every phase of chain either delegate the request to next phase or process it. But client need not to know these details unaware about the next phase.
Chain of responsibilities used widely used in web application to delegate the request for on layer to other layer like.
User Interface Layer -> Service Layer -> BO ->DAO layer
Chain of responsibility pattern is used in many web applications as explained below.
Case Study Requirements
I have ATM machine and I use 100, 500, 1000 rupee notes in it. Please develop a mock application to tell that the no of notes of each type that he will get for the amount that he wants with draw.
Implementation Proposal
Limitations in above approach
Structure
Code Example
Benefits and Liabilities
Loosely coupled as the sender and the receiver do not have idea on each other.
Processing mechanism may depend on different factors like parameters from the input or on input object type or on any other factor.
Difficult to analyze the chain it is more dynamic.
Points to Remember
Should have single super interface for all handler
Use all applicable existing handlers in the chain rather than creating new handler every time.
Use super interface reference in the successor link so that we need not to change the code if we change the handler.
When to use
When there are more levels of processing the request object divide each and every process into layers (or objects) and pass you request object to all layers (or objects) one after the other.
When the way of processing is changed dynamically, you can use this approach
Example from Java API
Servlet Filter is best example for chain of responsibilities.
Command Pattern
Definition
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Overview
As explained in the definition command pattern prepares the command and passes the command object to different layers or different environments and uses when never and where ever it is required. It may be used to perform undo operation by passing command object as an argument of undo() or it may be used to process sequential commands .
The Command pattern decouples the object that invokes the operation from the one having the knowledge to perform it. Command patters implementation is an object-oriented replacement for callbacks.
Call back method :
Here I want to give a realtime example, if your mobile is not reachable It will be redirected to you voice mail. Once I notice voice mail from you I will call you back when I am free. Same thing here also
Call back definition
A callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.
Command Patter can be used for multiple undo, redo operations.
Command pattern can be used in transaction management to implement rollback mechanism.
Each statement in transaction can be placed in a command object and can be undone If you want to roll back.
Case Study Requirements
Provide me a simple calculator that allows multiple undo redo operations
Naïve Implementation Proposal
Limitations in above approach
- In our application Calculation is primary requirement and with additional features like undo and redo. But CalC is not only bounded with actually business logic but also with additional features actual business logic tightly coupled with other features that impacts the cohesiveness of the class.
- In above example keeping track of operations is difficult
- P2I is not implemented here.
Structure
Code Example
Benefits and Liabilities
Command decouples the object that invokes the operation from the one that knows how to perform it.
Commands can be manipulated and extended like any other object.
You can assemble commands into a composite command. In general, composite commands are an instance of the Composite pattern.
It's easy to add new Commands, because you don't have to change existing classes.
Points to Remember
Command can have a wide range of Abilities. At one extreme item rely defines a binding between a receiver and the actions that carryout the request. Remove this line #####
Command interface should contain call back method i.e. execute () in our example
It should capable of performing undo redo operation.
When to use
When we want to implement call back methods we can use this pattern. Call back method is method that will be called at later point of time.
Example from Java API
Java.lang.Runnable
Iterator Pattern
Definition
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Overview
Iterator is used to traverse the aggregate object without exposing its underlying data structure. Traverse is defined as the process of visiting each element in the aggregate object. But iterating aggregate object depends on underlying data structure you are using. For example if aggregate object is a simple list we can use insertion order to traverse it and if aggregate object is a binary tree we may use pre-order, post-order or in-order to traverse it and some time It may be required to put constraints to access objects for example if you want to iterate only even numbers in number List. By considering all these kinds of requirements GOF provides one standard way to traverse all aggregate objects with the help of Iterator pattern as shown in below diagram. Do not confuse Below List with java.util.List.
In-fact Java collection framework is using this Iterator pattern. Here First () resets current passion as 0, Next () moves current position to next, IsDone () returns true if iteration is completed, CurrentItem () returns current Item that is pointed by the Iterator.
Structure
Code Example
Benefits and Liabilities
As discussed in definition.
Need not to expose underlying data structure.
Standard way to access all types of aggregate objects as shown in below figure
Traversing algorithm can be changed easily
Can be supported different types of traversing algorithms by introducing different iterators of each.
Points to Remember
Should follow proper traversing algorithm based on your implementation.
You can have more than one iterator at the same point of time.
#### Additional Logic can be added in iterator like adding constraints to filter the List.
Traverse algorithm can be implemented in either iterator or in aggregator itself. If the algorithm is implemented in aggregator then Iterator is used to store the state of the iteration. This kind of iterator is called as cursor.
Based on the handling of current Positions there are two types of Iterators
- External Iterator
- Internal Iterator
In External Iterators Client is responsible to change index positions and controlling the iterator whereas in Internal Iterator, Iterator is itself responsible to change index positions when client calls the Next() method index will be changed automatically. It is what happening with Java.util.Iterator().
When next() is called, below two operations are performed
- Current Item will be returned
- Index will be moved to next position
External Iterators are error prone. There may be chances to forget to update index by the client.
If item is added or deleted from List while traversing, Iterator will not identify those changes and cannot process newly added/removed element. Our iterator can use one of below solutions to it Robust.
- Notify to iterator when list is modified by using observer-observable pattern. So that iterator can adjust itself.
- Notify to iterator when list is modified by using observer-observable pattern. So that it may through the exception
Java utils Iterators through ConcurrentModificationException in the above case.
Null Iterator
Null iterator is an iterator whose isDone() returns always true. It is useful while traversing composite kind of objects. In composite you can consider all leaf element’s iterators or Null Iterators.
When to use
When there are collection of objects and wants to provide uniformed traversing mechanism for all collections.
When you want to provide traverse mechanism without exposing internal representation, you can go for iterator pattern.
Example from Java API
Java util Iterators are good examples for internal Iterators
Mediator Pattern
Definition
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.
Overview
Every solution in Object Oriented Program is the collection of object and interactions among those objects. Let us assume we have 100 objects and any change in object is required to update remaining Objects. To server these operation at least we need 100 operations. But there should be someone to monitor and control this. Mediator Patter will do the same. Below example tells how Mediator patter helps us to co-ordinate the communication among the objects by loosely coupling .
Real world example for mediator patter is Telephone exchange and even Air Traffic Controller. Mediator pattern is just centralized system to communicate with all others. We can take another example also. Mediator
Case Study Requirements
I am working in company in finance team. Please develop software application where I can enter basic salary and that should to return LTA, PF and all other components of an Employee. Please refer below link for more details http://www.citehr.com/430310-salary-structure-components-variable-pay.html or http://hrlink.in/topics/standard-salary-structure
1) Basic - 35% - 50% of Gross
2) HRA - 40% of Basic for Non metro & 50% of basic for Metro
3) Con - Max Rs. 800/ P M which is Max of Rs. 9600 P A
4) Medical Reim - Max Rs. 1250 / PM which can be max of Rs 15000 PA
5) Spl Allow - Balance of Gross will be provided as Spl Allow
Statutory
1) PF
Emp Contribution - 12% on Basic
Emp'r Contribution - 13.61% on basic
2) ESI - Applicable to employees whose Gross Salary is less than or equal to Rs.10000
Emp Contribution - 1.75% on Grorss
Emp'r Contribution - 4.75% on Gross
PT - It Varies State to state
Net Salary = Gross - PF (Emp Cont) - ESI (Emp Cont) - PT
CTC = Gross + PF (Emp'r Cont) - ESI (Emp'r Cont)
Gratuity = Basic *15/26 - It is payable to the employee who completes 5yrs of service in the organisation. It can be showed as a part of CTC.
2) HRA - 40% of Basic for Non metro & 50% of basic for Metro
3) Con - Max Rs. 800/ P M which is Max of Rs. 9600 P A
4) Medical Reim - Max Rs. 1250 / PM which can be max of Rs 15000 PA
5) Spl Allow - Balance of Gross will be provided as Spl Allow
Statutory
1) PF
Emp Contribution - 12% on Basic
Emp'r Contribution - 13.61% on basic
2) ESI - Applicable to employees whose Gross Salary is less than or equal to Rs.10000
Emp Contribution - 1.75% on Grorss
Emp'r Contribution - 4.75% on Gross
PT - It Varies State to state
Net Salary = Gross - PF (Emp Cont) - ESI (Emp Cont) - PT
CTC = Gross + PF (Emp'r Cont) - ESI (Emp'r Cont)
Gratuity = Basic *15/26 - It is payable to the employee who completes 5yrs of service in the organisation. It can be showed as a part of CTC.
Implementation Proposal
Limitations in above approach
Above approach is simple but not loosely coupled. No control on object communication.
Structure
Code Example
Producer and consumer problem is another good example here
Benefits and Liabilities
As discussed in definition All colleagues are loosely coupled.
Centralized monitor on object communication.
Easy to modify any colleague.
Addition or deletion of a colleague is simple.
If the behavior is changed we can extend Mediator with new logic easily
Points to Remember
When to use
Example from Java API
Java.util.Timer class scheduleXXX() methods
Memento Pattern
Definition
Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
Overview
Memento is an object that stores a snapshot of the internal state of another object the memento's originator.
Case Study Requirements
Please provide me an editor where I can restore previous versions of the file, For example If I save a file It should create a version and If I press again I should create one more version of the file. But when I select the time stamp the file is required to be restored. Just like ”UNDO”.
Implementation Proposal
Limitations in above approach
Structure
Memento
- Stores internal state of the Originator object. The memento may store as much or as little of the originator’s internal state as necessary at its originator's discretion.
- Protects against access by objects other than the originator. Mementos have effectively two interfaces. Caretaker sees a narrow interface to the Memento—it can only pass the memento to other objects. Originator, in contrast, sees a wide interface, one that lets it access all the data necessary to restore itself to its previous state. Ideally, only the originator that produced the memento would be permitted to access the memento's internal state.
· Originator
- Creates a memento containing a snapshot of its current internal state.
- Uses the memento to restore its internal state.
Caretaker (mechanism to handle memento)
- Is responsible for the memento's safekeeping.
- Never operates on or examines the contents of a memento.
Code Example
When to use
When you want to reuse previous state of any object you can go for Memento. One of the examples like undo, redo operations on your GUI based application.
Observer Pattern
Definition
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Overview
Sometimes we need to inform to all observers once the state of any object (Subject) is changed. If we consider real time example, The most popular social sites like facebook, Google Plus, If any user updates his album or any other component It will be notified to all his friends. We can consider youtube also as an another example, once you subscribe to any account, when account owner adds any new video Notification will be sent to all subscribers through mails.
So here you have two object mainly subject and observers. All observers are required to be registered with Subject. For a single subject can have more than one observer.
When any change is done in subject, Notification will be sent to all its observers. In response each observer will send a query to synchronize its state with subject. This is also called publish-subscribe methodology.
Case Study Requirements
Take above Facebook/Youtube example and develop an application.
Structure
#### setState notify in diagram ####
In above diagram subject’s state has been changed by aConcreteObserver. And subject notifies all its observers by calling update method, then observers call getState() method to sync with subject, Note that aConcreteObserver is changing the subject but not updating itself until it receives the notification from subject.
Notify can be called in two ways
- Notify can be called by subject itself.
- Notify can be called by Client that who changes it
Advantage of first is, Client need not to remember to call notify(), so there is no chance of missing to send notification after changing the subject. But there is a disadvantage, for example if Client wants to notify, once he completes all changes on the subject, he cannot do that if we follow first case, so that no of notifications will be increased to all observers.
If you follow second, Client can send notification once all his operations are done on the subject. But disadvantage is that client may for get to call notify().
Benefits and Liabilities
Observer and subjects are loosely coupled.
All observers are always will be in sync with subject
Points to Remember
Make sure to send notification to all observers and then all observers should send a query to synchronize its state.
Do not for get to handle the case of deletion of a Subject. If any subject is deleted notify the same to all its observers so that they take necessary actions. ###### ….
When to use
When you want to notify changes done in one subject to many Observers
Example from Java API
Java.util.Observer, Java.util.Observable
State Pattern
Definition
Allow an object to alter its behavior when it’s internal state changes. The object will appear to change its class.
Overview
State means “The way something is with respect to its main attributes”. We can find different states in the Project Life Cycle. We can find different states in Human Life. Even we can find different states in life cycle of Thread. The behavior of Human/Thread/Project is different for different states. For example if thread is in sleep state it acts in one way and if the same thread in blocked state it acts in another way. If Project is in analysis state team focuses on documentation work. If project is development state again it focuses on code development. So once state is changed behavior also changed. We can take bike it has different 5 gears we can consider each gear is a state and each state as its own behavior for example if in first gear we can observe high pick up and low speed where as in lost gear high speed and low gear.
As per the definition State pattern allows to change object’s behavior once its internal state changes.
Case Study Requirements
I am CEO of CAR company and for one our car model we want to provide a LCD screen that displays the speed and acceleration range based on the gear that the car uses right now.
Implementation Proposal
Limitations in above approach
Structure
Code Example
Benefits and Liabilities
State Pattern encapsulates the state and its behavior.
Makes application more comfortable to add or remove states easily
Disadvantage of this approach as no of states increased no of subclasses will be increased. It affects the compactness of the application. But even as state and behavior are encapsulated maintaining them is easy even when states are very huge in number otherwise application may be messed up with large no of conditional statements.
State Transition is easy.
Points to Remember
We can create state object in two ways
- At runtime whenever required and destroy after its usage
- Creating at the starting of application
Use first approach if the State Object has more information. Why because it will create only required no of objects so memory will be used efficiently.
Use second approach if states are changed frequently, If any state is changed just you will change the corresponding attribute. If you use first approach here creating and destroying objects will consume more time
When to use
An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.
Strategy Pattern
Definition
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it
Overview
Strategy as name indicates that it depends on the strategy that you want to follow. It makes your application more loosely coupled with the algorithm. You can change the algorithm based on your strategy. Here I have an example where we use in real life about the strategy.
For Example. If we want to go to KPHB from Ameerpet, We know there are two was one is via Bhrath Nagar and other is via BalNagar. BalNagar route is little bit far but with less traffic. Bharath Nagar route is nearer but with heavy traffic. I will decide the route based on the journey time. If it is morning till 8:30 I will choose Barath Nagar route else I will choose BalNagar route. Here my strategy is Timing. Usually at 8:30 am Barath Nagar route is free.
Same way strategy pattern follows, For every problem we may have more than on algorithm to solve it. Based on my requirement I will choose one of them based on space/time trade-offs
Case Study Requirements
I need a data structure that allows either add/delete objects optimally or to traverse the elements based on my strategy that can be chosen at the time of creating my data structure.
Structure
Benefits and Liabilities
Strategy Pattern avoids usage of conditional statements like if-else.
Algorithm will be chosen at runtime.
Drawback of this approach is, when we use inheritance and one sub class for each algorithm, you will have lots of subclasses and communication among Strategies and Contexts is extra burden to the application.
No of Objects used is proportion to the no of strategies
Points to Remember
Use generics for Strategies so that you need not to change it at runtime.
When to use
When you have many strategies with different algorithms for different strategy. And you want to choose strategy at runtime.
An algorithm uses data that clients shouldn't know about that data
Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.
Example from Java API
Java.util.Compartor is best example for Strategy from java API
Collections.sort(java.util.List, java.util.Comparator) based on the strategy we can pass comparison logic at runtime.
And also service method of HttpServlet method.
Thank you Amar
ReplyDeleteThis blog contains detail information on Java Design Patterns...This blog is awesome...it helps anyone who is preparing for OCMJEA..Thank you Paramesh Sir
ReplyDelete