Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Friday, October 23, 2015

Design pattern - Strategy pattern

Description:
Define a family of algorithms, encapsulate each one and make it interchangeable. Strategy lets the algorithm vary independently from the client use it.

In short - "Encapsulates an algorithm inside a class"

Problem:
Sometimes new behavior or algorithm or action on related objects are changed or new implementation needs to be provided. Using interface leaves each concrete class to have it's own implementation, no way to reuse/leverage exists implementation. Using class inheritance leaves in situation where all sub classes are forces to provide implementation of the behavior even not appropriate to that sub class.
Strategy pattern encapsulates set of behaviors/algorithms/actions in a separate hierarchy allowing client to use algorithm without knowing implementation and run time change of algorithm. Other hand behavioral implementation changes can be done without affecting client.

How to use Strategy pattern:
1. Concepts involved in Strategy pattern, 'context', 'abstract behavior', 'concrete behavior' 

2. Create an interface 'behavior' with abstract method (like execute/do). 

3. Create derived concrete class(es) from 'behavior' base class which will provide the implementation of the abstract method(s) of interface. Each concrete class will have alternative implementation detail

4. Need to create separate behavior interface and concrete class creation for each set of behaviors

5. Client will create an instance of concrete behavior and store it in abstract reference. Client class will have a entry point (a method) which will make the abstract method call on abstract reference

  • Most of the times, client side has a hierarchy where concrete classes derived from an abstract class, the abstract class holds the reference of strategy provided by concrete class and has a method to make a call to abstract strategy reference without knowing the actual concrete class.

Class diagram:























Examples:
1. Duck pond simulation game from Head First Design Pattern. The large variety of duck species can swim but in need of adding behaviors like fly, make quacking sounds on some specific kind of ducks. Fly behavior can be externalized through strategy and ducks would just use composition of fly behavior.

2. Modes of transportation to an airport is an example of a Strategy. Several options exist such as driving one's own car, taking a taxi, an airport shuttle, a city bus, or a limousine service. For some airports, subways and helicopters are also available as a mode of transportation to the airport. Any of these modes of transportation will get a traveler to the airport, and they can be used interchangeably. The traveler must chose the Strategy based on tradeoffs between cost, convenience, and time. (Resources-2)

3. A car objects break behavior can be considered as strategy where regular break or ABS break can be used based on need.

Benefits:
1. Decouples the algorithm/behavior from client who would use it
2. Allows client to pick any implementation of algorithm/behavior
3. Allows algorithms/behaviors to interchange without affecting client
Notes:
1. Strategy pattern uses composition between objects rather than inheritance 
2. Follows 'Open/Closed Principle' of OO Design Principle
3. Abstract coupling - client is coupled only to an abstraction and not a particular realization of that abstraction
4. Ideally client should have a mean (mostly using setter method) to change strategy


Things to check back:
1. Coexistence with other patterns


Resources:
1. Head First Design Pattern
2. https://sourcemaking.com/design_patterns
3. https://en.wikipedia.org/wiki/strategy_pattern

Friday, October 16, 2015

Design Pattern - Command pattern

Description:
The command pattern encapsulates a request as an object to perform an operation on an object (receiver). This allows client to parameterize other objects (invoker) with different requests, queue or log requests, and support undoable operations.

In short - "Encapsulate a command request as an object"


Problem:
Need to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.

How to use Command pattern:
1. Concepts involved in Command pattern, 'receiver', 'invoker' and 'command'

2. Create an interface 'command' with abstract method 'execute'

3. Create derived concrete class(es) from 'command' base class which encapsulates a 'receiver', a method to invoke and the arguments to pass

4. 'Receiver' is actually responsible to perform the desired action which is encapsulated in the 'command' as attribute. Mostly passed to command through constructor

5. 'Invoker' gets the command object(s) through method like 'setCommand(Command)' and provides a mean to make a call to 'command' class's 'execute' method

6. Client of Command pattern creates a concrete 'command' object, passes reciever to it and sets it to 'invoker' by making call to 'setCommand(Command)'. Later client asks 'invoker' to execute the command.

Class diagram:


























Benefits:
1. decouples the object that invokes the operation from the one that know how to perform it
2. Allows parameterization of clients with different requests
3. Allows invoker to save request in a queue
4. Undo and redo functionality can be implemented as 


Notes:
1. Macro Command - represents set of commands to be performed on call to be executed. Macro commands can be implemented as Composite, can also have other operation like undo, redo, forward/backward traversing, logging, queue etc.
2. Undo/redo action - can be performed two ways
  • Store receiver's previous state in memory
  • Store set of performed actions on receiver in memory
3. Queuing the requests - as the commands are isolated from invoker, those can be executed asynchronously in background of an application. Usually invoker keeps a set of commands, runs in main thread and action request to receiver can happen in a separate thread. To have faster processing, multi-thread can be considered to run through the set of commands. Scheduler, thread pool, job queues etc. applications can be considered as good example of this scenario.



Things to check back:
1. Coexistence with other patterns
2. Alternates of Command patterns


Resources:
1. Head First Design Pattern
2. https://sourcemaking.com/design_patterns
3. https://en.wikipedia.org/wiki/command_pattern

Thursday, October 15, 2015

Design Pattern - Iterator pattern

Description:
"The Iterator Pattern provides a way to access the elements of an aggregate object without exposing its underlying representation".

This simplifies aggregate interface and implementation by placing traversal responsibility on iterator and this traversal of a collection is promoted to a full object comparing to a logic embedded in the aggregate.  In the process helping the client of aggregate object a polymorphic traversal.

In short - "Sequentially access the elements of a collection"


How to use Iterator pattern:
1. Two types of objects needed, one is called 'aggregate', other is called 'iterator'

2. "Aggregate" abstraction should have a method (i.e. createIterator) to create corresponding iterator

3. Each derived concrete class of aggregate base class has to provide implementation of the abstract method (i.e. createIterator)

4. Create abstract "iterator" base which can have method like next, hasNext, remove. See Note-3 and 4 to know more 

5. Each derived concrete class of "iterator" base class should provide implementation of methods described in the "iterator".

6. The client will create necessary aggregate object based on collection structure and ask for "iterator" from the aggregate object which will return a concrete iterator as generic type. 



Class diagram:





















Benefit:
1. Aggregate object can have it's encapsulation intact without exposing how the collection structure is defined
2. Allows the client to traverse different ways
3. Supports multiple simultaneous traversal on a collection
4. Provides uniform interface to traverse heterogeneous collections


Notes:

1. Internal Iterator vs External Iterator - java.util.Iterator is an external iterator as client has to control the iteration. Internal iterator is controlled by the iterator itself and client has to inform the iterator needs to be done as it iterator through.

2. Robust Iterator - the iterator can provide both insertion and deletion during traversal and doesn't make a copy of the aggregate. This iterator makes sure the element(s) not fetched twice or skipped due to insert or delete in the collection. 

3. java provides java.util.Iterator which can be used in most of the cases. This interface has three methods (next, hasNext, remove). If derived concrete Iterator doesn't need to support for remove method, java.lang.UnsupportedOperationException can be thrown.

4. An Iterator can be defined to move backwards as well forwards. Java provides such interface java.util.ListIterator with next, hasNext, previous, hasPrevious, remove methods along with other like (nextIndex, previousIndex, set, add).

Things to check back:
1. How to write a thread safe, robust Iterator


Resources:
1. Head First Design Pattern
2. https://sourcemaking.com/design_patterns
3. https://en.wikipedia.org/wiki/Iterator_pattern 

Tuesday, October 13, 2015

Design Pattern - Visitor pattern

Definition:
From gang of four -  "Represent 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".

Head First - "Use the Visitor pattern when you want to add capabilities to a composite of objects and encapsulation is not important".

In short - "Defines a new operation to a class without change"

How to use Visitor pattern:
1. Two types of objects needed, one is called 'element', other is called 'visitor'

2. Create a base visitor class hierarchy with "visit" method for each concrete derived class the composite hierarchy. Each "visit" method accepts a single argument - reference to the original element derived class

3. Each derived concrete class of visitor base class has to provide implementation of each "visit" method

4. Add abstract/virtual "accept" method in base element hierarchy. This takes an argument of abstract base class of visitor hierarchy 

5. All sub-element or derived concrete classes has to provide implementation of "accept" method by simply calling "visit" method of passed concrete Visitor class where "this" is passed as reference

6. For any operation needed for client will create and instance of concrete visitor class and pass that as reference to "accept" method in each concrete element class. The client of Visitor pattern is called traverser which knows how to guide the visitor through the composite structure. 

Class diagram:


















Examples:
1. A restaurant Application might have menu, menu item and ingredient objects with related attributes and operations. If reality changes where customers demand nutritional information on menu items as well as on ingredients, rather making elements (menu, menu item, ingredient etc) level changes visitor pattern can be implemented.

2. A Shopping cart where we can add different type of items (Elements), when we click on checkout button, it calculates the total amount to be paid. Now we can have the calculation logic in item classes or we can move out this logic to another class using visitor pattern

Benefit:
1. Allows to add operations/functionalities to a composite structure without changing the structure itself
2. Adding new operations/functionalities is relatively easy
3. The code for operations performed by the Visitor is centralized

Trade-off:
1. The composite classes' encapsulation is broken when the visitor pattern is used
2. Because the traversal function is involved, changes to composite structure are more difficult


Notes:
1. Double dispatch - the operation executed depends on: the name of the request (method name), and the type of TWO receivers (the type of the Visitor and the type of the element it visits)

From above class diagram double dispatch can be as below - 
  • When the accept method is called in the program, its implementation is chosen based on both: 
    • The dynamic type of the element. 
    • The static type of the visitor. 
  • When the associated visit method is called, its implementation is chosen based on both: 
    • The dynamic type of the visitor. 
    • The static type of the element as known from within the implementation of the accept method, which is the same as the dynamic type of the element. (As a bonus, if the visitor can't handle an argument of the given element's type, then the compiler will catch the error.) 
  • Consequently, the implementation of the visit method is chosen based on both: 
    • The dynamic type of the element. 
    • The dynamic type of the visitor.

2. A more flexible approach to this pattern is to create a wrapper class implementing the interface defining the accept method. The wrapper contains a reference pointing to the 'abstract base element' which could be initialized through the constructor. This approach avoids having to implement an interface on each element. (Resource-04)


Resources:
1. Head First Design Pattern
2. https://sourcemaking.com/design_patterns
3. https://en.wikipedia.org/wiki/Visitor_pattern
4. Java Tip 98: Reflect on the Visitor design pattern.