Prototype Design Pattern

Download the working example demo code in java from my GIT repository –https://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects

Code Example
The Prototype pattern specifies the kind of objects to create using a prototypical instance. Cell is the abstract class with different subclasses like singleCell Organism, amoeba, bacteria etc. For each sub class a breeder object is created before hand and registered in SpecimenCache.java class. Now whenever client program wants to breed or culture a particular organism say amobea they will fetch it from cache and invoke split/clone method which will provide replicated organism with same state property. Download the example code and have fun.
 Example of Prototype

When creating an object is time consuming and a costly affair and you already have a most similar object instance in hand, then you go for prototype pattern. Instead of going through a time consuming process to create a complex object, just copy the existing similar object and modify it according to your needs. Clone the existing instance in hand and then make the required update to the cloned instance so that you will get the object you need. Other way is, tweak the cloning method itself to suit your new object creation need.

Intent
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
  • Co-opt one instance of a class for use as a breeder of all future instances.
  • The new operator considered harmful.
Problem
Application “hard wires” the class of object to create in each “new” expression.
Discussion
Declare an abstract base class that specifies a pure virtual “clone” method, and, maintains a dictionary of all “cloneable” concrete derived classes. Any class that needs a “polymorphic constructor” capability: derives itself from the abstract base class, registers its prototypical instance, and implements the clone() operation.

The client then, instead of writing code that invokes the “new” operator on a hard-wired class name, calls a “clone” operation on the abstract base class, supplying a string or enumerated data type that designates the particular concrete derived class desired.

Prototype Design Pattern

Check list
Add a clone() method to the existing “product” hierarchy.
  1. Design a “registry” that maintains a cache of prototypical objects. The registry could be encapsulated in a new Factory class, or in the base class of the “product” hierarchy.
  2. Design a factory method that: may (or may not) accept arguments, finds the correct prototype object, calls clone() on that object, and returns the result.
  3. The client replaces all references to the new operator with calls to the factory method.
Rules of thumb
  • Prototype co-opts one instance of a class for use as a breeder of all future instances.
  • Prototypes are useful when object initialization is expensive, and you anticipate few variations on the initialization parameters. In this context, Prototype can avoid expensive “creation from scratch”, and support cheap cloning of a pre-initialized prototype.
  • Factory Method: creation through inheritance. Protoype: creation through delegation.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Protoype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
  • Prototype doesn’t require subclassing, but it does require an “initialize” operation. Factory Method requires subclassing, but doesn’t require Initialize.
  • Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well.
Advertisements

Bridge Design Pattern

Download the working example demo code in java from my GIT repository –https://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects

Example Code description :
TV and remote are 2 separate entities. As an architect of remote one way is to abstract all remote in an interface and develop it, however the challenge is in the way both TV and remote development is getting mixed or interlocked – in technical terms getting tightly coupled. Changes in one might effect the another. So to solve it, We have created a bridge between TV and remote. Thus decoupled TV and Remote. Please download example and try on your own.

bridge2

Definition :
“Decouple an abstraction from its implementation so that the two can vary independently” is the intent for bridge design pattern as stated by GoF.
Bridge design pattern is a modified version of the notion of “prefer composition over inheritance”.Decouple implentation from interface and hiding implementation details from client is the essence of bridge design pattern.

Bridge is used where we need to decouple an abstraction from its implementation so that the two can vary independently.

This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract class by providing a bridge structure between them.

This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. Both types of classes can be altered structurally without affecting each other.

Elements of Bridge Design Pattern

  • Abstraction – core of the bridge design pattern and defines the crux. Contains a reference to the implementer.
  • Refined Abstraction – Extends the abstraction takes the finer detail one level below. Hides the finer elements from implemetors.
  • Implementer – This interface is the higer level than abstraction. Just defines the basic operations.
  • Concrete Implementation – Implements the above implementer by providing concrete implementation.

bridge

Summary of Bridge Design Pattern

  • Creates two different hierarchies. One for abstraction and another for implementation.
  • Avoids permanent binding by removing the dependency between abstraction and implementation.
  • We create a bridge that coordinates between abstraction and implementation.
  • Abstraction and implementation can be extended separately.
  • Should be used when we have need to switch implementation at runtime.
  • Client should not be impacted if there is modification in implementation of abstraction.
  • Best used when you have multiple implementations.

bridgeColor

Bridge Vs Adapter Design Pattern

The adapter design pattern helps it two incompatible classes to work together. But, bridge design pattern decouples the abstraction and implementation by creating two different hierarchies.

Is MVC one of the GoF (Gang-of-Four) patterns?

MVC is not one of the GoF patterns. They are not at the same level. MVC is what is called an architectural pattern while GoF patterns are design patterns. Basically MVC is a compound pattern (combination of more than 1 design pattern), that means it is a guide line and could be implemented using several other design patterns.

However, when implementing MVC you can take advantage of existing patterns. Take the Head First Design Patterns book they build MVC using Strategy, Composite, and Observer pattern. And I’m sure that there exists other implementations of the MVC pattern using other design patterns. I have also seen MVC being done using the Command pattern.
Needless to say, even though MVC is not a GoF pattern, it is still a very useful one. GoF patterns are only a few of all existing patterns out there.

Proxy Design Pattern

Download the working example demo code in java from my GIT repository –https://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects
Code example Description :
Doctors are busy and uses proxies / surrogates or say assistant doctors, unless they are not needed. For initial investigation  senior doctor or surgeon is not required, hence they make you to interact with their proxy/assistant doctor. However, for operation or consulting they take the charge (replaces the proxy).

Proxy

Proxy means ‘in place of’. In attendance roll call, we give proxy for our friends in college right? ‘Representing’ or ‘in place of’ or ‘on behalf of’ are literal meanings of proxy and that directly explains proxy design pattern. It is one of the simplest and straight forward design pattern.

Intent :
Provide a surrogate or placeholder for another object to control access to it.
Use an extra level of indirection to support distributed, controlled, or intelligent access.
Add a wrapper and delegation to protect the real component from undue complexity.

Problem :
You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client.

Possible Usage Scenarios :
Remote Proxy – Represents an object locally which belongs to a different address space. Think of an ATM implementation, it will hold proxy objects for bank information that exists in the remote server. RMI is an example of proxy implmenetation for this type in java.
Virtual Proxy – In place of a complex or heavy object use a skeleton representation. When an underlying image is huge in size, just represent it using a virtual proxy object and on demand load the real object. You feel that the real object is expensive in terms of instantiation and so without the real need we are not going to use the real object. Until the need arises we will use the virtual proxy.
Protection Proxy – Are you working on a MNC? If so, you might be well aware of the proxy server that provides you internet. Saying more than provides, the right word is censores internet. The management feels its better to censor some content and provide only work related web pages. Proxy server does that job. This is a type of proxy design pattern.
Smart Reference – Just we keep a link/reference to the real object a kind of pointer.

Structure

By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.

ProxyStructure

Discussion :
Design a surrogate, or proxy, object that: instantiates the real object the first time the client makes a request of the proxy, remembers the identity of this real object, and forwards the instigating request to this real object. Then all subsequent requests are simply forwarded directly to the encapsulated real object.

There are four common situations in which the Proxy pattern is applicable.
A virtual proxy is a placeholder for “expensive to create” objects. The real object is only created when a client first requests/accesses the object.
A remote proxy provides a local representative for an object that resides in a different address space. This is what the “stub” code in RPC and CORBA provides.
A protective proxy controls access to a sensitive master object. The “surrogate” object checks that the caller has the access permissions required prior to forwarding the request.
A smart proxy interposes additional actions when an object is accessed. Typical uses include:

Important Points:
A proxy may hide information about the real object to the client.
A proxy may perform optimization like on demand loading.
A proxy may do additional house-keeping job like audit tasks.
Proxy design pattern is also known as surrogate design pattern.

Check list :
Identify the leverage or “aspect” that is best implemented as a wrapper or surrogate.
Define an interface that will make the proxy and the original component interchangeable.
Consider defining a Factory that can encapsulate the decision of whether a proxy or original object is desirable.
The wrapper class holds a pointer to the real class and implements the interface.
The pointer may be initialized at construction, or on first use.
Each wrapper method contributes its leverage, and delegates to the wrappee object.

Rules of thumb :
Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface.
Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests.

Template Method Design Pattern

Download the working example demo code in java from my GIT repositoryhttps://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects

Example Code Briefings : Template Method Fruit Juice extraction example defines a recipe (with exact steps and quantity) to prepare the drink which is kept in the extract class. However the flavor of the fruit Juice can be changed by it subclasses by overriding (which is defined as hooks/abstractor in parent abstract class).

Intent:
Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
Base class declares algorithm ‘placeholders’, and derived classes implement the placeholders.

Problem:
Two different components have significant similarities, but demonstrate no reuse of common interface or implementation. If a change common to both components becomes necessary, duplicate effort must be expended.

Definition:
Template method design pattern is to define an algorithm as skeleton of operations and leave the details to be implemented by the child classes. The overall structure and sequence of the algorithm is preserved by the parent class.
The component designer decides which steps of an algorithm are invariant (or standard), and which are variant (or customizable). The invariant steps are implemented in an abstract base class, while the variant steps are either given a default implementation, or no implementation at all. The variant steps represent “hooks”, or “placeholders”, that can, or must, be supplied by the component’s client in a concrete derived class.

The component designer mandates the required steps of an algorithm, and the ordering of the steps, but allows the component client to extend or replace some number of these steps.

Template Method is used prominently in frameworks. Each framework implements the invariant pieces of a domain’s architecture, and defines “placeholders” for all necessary or interesting client customization options. In so doing, the framework becomes the “center of the universe”, and the client customizations are simply “the third rock from the sun”. This inverted control structure has been affectionately labelled “the Hollywood principle” – “don’t call us, we’ll call you”.

Template Method scheme

Structure:
Template Method scheme
The implementation of template_method() is: call step_one(), call step_two(), and call step_three(). step_two() is a “hook” method – a placeholder. It is declared in the base class, and then defined in derived classes. Frameworks (large scale reuse infrastructures) use Template Method a lot. All reusable code is defined in the framework’s base classes, and then clients of the framework are free to define customizations by creating derived classes as needed.

Example:
Daily routine of a worker.

Template Method example

Rules of thumb:
Strategy is like Template Method except in its granularity.
Template Method uses inheritance to vary part of an algorithm. Strategy uses delegation to vary the entire algorithm.
Strategy modifies the logic of individual objects. Template Method modifies the logic of an entire class.
Factory Method is a specialization of Template Method.

Composite Design Pattern

Download the working example demo code in java from my GIT repository –https://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects

Intent:
Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Recursive composition
“Directories contain entries, each of which could be a directory.”
1-to-many “has a” up the “is a” hierarchy

What is Whole-part Hierarchy :
A system consists of subsystems or components. Components can further be divided into smaller components. Further smaller components can be divided into smaller elements. This is a part-whole hierarchy.
 
Problem:
Application needs to manipulate a hierarchical collection of “primitive” and “composite” objects. Processing of a primitive object is handled one way, and processing of a composite object is handled differently. Having to query the “type” of each object before attempting to process it is not desirable.
 

Tree for Composite
When we get a recursive structure the obvious choice for implementation is a tree. In composite design pattern, the part-whole hierarchy can be represented as a tree. Leaves (end nodes) of a tree being the primitive elements and the tree being the composite structure.
 composite1
 
Uml Design for Composite Pattern

Component: (structure)

    Component is at the top of hierarchy. It is an abstraction for the composite.
    It declares the interface for objects in composition.
    (optional) defines an interface for accessing a component’s parent in the recursive structure, and implements it if that’s appropriate.

Leaf: (primitive blocks)

    The end nodes of the tree and will not have any child.
    Defines the behaviour for single objects in the composition

Composite: (group)

    Consists of child components and defines behaviour for them
    Implements the child related operations.
 composite

 
Important Points:
Recursive formation and tree structure for composite should be noted.
Clients access the whole hierarchy through the components and they are not aware about if they are dealing with leaf or composites.
Importance of composite pattern is, the group of objects should be treated similarly as a single object.
Being able to treat a heterogeneous collection of objects atomically (or transparently) requires that the “child management” interface be defined at the root of the Composite class hierarchy (the abstract Component class). However, this choice costs you safety, because clients may try to do meaningless things like add and remove objects from leaf objects. On the other hand, if you “design for safety”, the child management interface is declared in the Composite class, and you lose transparency because leaves and Composites now have different interfaces.

compsiteStructure

Rules of thumb
Composite and Decorator have similar structure diagrams, reflecting the fact that both rely on recursive composition to organize an open-ended number of objects.
Decorator is designed to let you add responsibilities to objects without subclassing. Composite’s focus is not on embellishment but on representation. These intents are distinct but complementary. Consequently, Composite and Decorator are often used in concert.

Iterator Design Pattern

Download the working example demo code in java from my GIT repository –https://github.com/premaseem/designPatterns/blob/4f171f69bbeb34e614a6ed6d6e68df342e18d90c/ZipDownloadableProjects/IteratorPatternEmployeeExample.zip

To see code visit diff link:https://github.com/premaseem/designPatterns/commit/af9228704b70742e13f4264558ddf4e59f2b0073

Intent
Explicitly separate the notion of “algorithm” from that of “data structure”.
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
The key idea is to take the responsibility for access and traversal out of the aggregate object and put it into an Iterator object that defines a standard traversal protocol.

Problem solved by pattern
Need to “abstract” the traversal of wildly different data structures so that algorithms can be defined that are capable of interfacing with each transparently.

Iterators in Java

“An aggregate object such as a list should give you a way to access its elements without exposing its internal structure. Moreover, you might want to traverse the list in different ways, depending on what you need to accomplish. But you probably don’t want to bloat the List interface with operations for different traversals, even if you could anticipate the ones you’ll require. You might also need to have more than one traversal pending on the same list.” And, providing a uniform interface for traversing many types of aggregate objects (i.e. polymorphic iteration) might be valuable.

The Iterator pattern lets you do all this. The key idea is to take the responsibility for access and traversal out of the aggregate object and put it into an Iterator object that defines a standard traversal protocol.

The Iterator abstraction is fundamental to an emerging technology called “generic programming”. This strategy seeks to explicitly separate the notion of “algorithm” from that of “data structure”. The motivation is to: promote component-based development, boost productivity, and reduce configuration management.

Key Notes on Iterator in Java:
Iterator in Java basically is used to support generics thereby making it mandatory to make use of the Generic version of Iterator and not the Iterator with raw type.
In case the objects need to be removed from the Collection, in that case do not make use of for-each loop. Instead one can make use of Iterator’s remove() method to avoid any ConcurrentModificationException.
As far as Iterating over collection with the help of Iterator concerned, it is subject to ConcurrentModificationException if Collection is modified after Iteration started. However this is meant to take place only in case of fail-fast Iterators.
We have fail-fast and fail-safe type of Iterators in Java and you need to check for the difference between these types.
List collection type is also known to supports ListIterator that comprises of add() method so as to incorporate elements in collection at the time of iteration. Difference between Iterator and ListIterator has also been discussed above.

External vs Internal Iterator
When the client controls the iteration sequence and index position then it is called as the external iterator. Otherwise if the iterator controls the traversal then it is called internal iterator. On external iterator, the design is that the invoking client code should explicitly invoke the method to move the pointer to next element. For internal iterator, when an element is accessed, after access the pointer will be automatically moved to next index by the iterator. In general internal iterators are easier to use than the external iterators.