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.

State design Pattern

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

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

The state pattern, which closely resembles Strategy Pattern, is a behavioral software design pattern, also known as the objects for states pattern. This pattern is used in computer programming to encapsulate varying behavior for the same routine based on an object’s state object. This can be a cleaner way for an object to change its behavior at runtime without resorting to large monolithic conditional statements.
In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.

Problem solved by State pattern

A monolithic object’s behavior is a function of its state, and it must change its behavior at run-time depending on that state. Or, an application is characterixed by large and numerous case statements that vector flow of control based on the state of the application.

Different between State and Strategy

Strategy Pattern is used when the whole algorithm is changed to another algorithm and the client is responsible for that, whereas, in State Pattern, the class itself manages the strategy based on the state. Two patterns are pretty similar in practice, and the defining difference between them tends to vary depending on who you ask. Some popular choices are:
States store a reference to the context object that contains them. Strategies do not.
States are allowed to replace themselves (IE: to change the state of the context object to something else), while Strategies are not.
Strategies are passed to the context object as parameters, while States are created by the context object itself.
Strategies only handle a single, specific task, while States provide the underlying implementation for everything (or most everything) the context object does.

Code example description :

The treatment is given to patient based on the their state. For example providing one remdy lets say supplying oxygen might help unstable patient, however it can cause reaction or side effect to stable patient. In the example, user can pick up different treatment and based on that state of patient might change. Feel free to download and try.

What is Singleton design pattern ?

Checkout the working code from my git hub repository using below link. It contains all possible ways of implementation of singleton with multi-thread issue which creates multiple instance of singleton.

https://github.com/premaseem/designPatterns/tree/master/SingletonPattern/src/com/premaseem/singleton

Singleton is a part of Gang of Four design pattern and it is categorized under creational design patterns.


In Java the Singleton pattern will ensure that there is only one instance of a class is created in the Java Virtual Machine. It is used to provide global point of access to the object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. In terms of practical use Singleton patterns are used in logging, caches, thread pools, configuration settings, device driver objects.
For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time.

What is Abstract Factory Design Pattern ?

Download the working code from my git hub repository from this link https://github.com/premaseem/designPatterns/tree/master/AbstractFactoryPattern

Basic Definition of Abstract Factory :

Abstract Factory patterns works around a super-factory which creates other factories. This factory is also called as Factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

In Abstract Factory pattern an interface is responsible for creating a factory of related objects, without explicitly specifying their classes.

 

AbstractFactory1

 

The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.[1] In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the theme. The client doesn’t know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products.[1] This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.[2]

An example of this would be an abstract factory class DocumentCreator that provides interfaces to create a number of products (e.g. createLetter() and createResume()). The system would have any number of derived concrete versions of the DocumentCreator class like FancyDocumentCreator or ModernDocumentCreator, each with a different implementation of createLetter() and createResume() that would create a corresponding object like FancyLetter or ModernResume. Each of these products is derived from a simple abstract class like Letter or Resume of which the client is aware. The client code would get an appropriate instance of the DocumentCreator and call its factory methods. Each of the resulting objects would be created from the same DocumentCreator implementation and would share a common theme (they would all be fancy or modern objects). The client would only need to know how to handle the abstract Letter or Resume class, not the specific version that it got from the concrete factory.

A factory is the location of a concrete class in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage and to create families of related objects without having to depend on their concrete classes.[2] This allows for new derived types to be introduced with no change to the code that uses the base class.

Use of this pattern makes it possible to interchange concrete implementations without changing the code that uses them, even at runtime. However, employment of this pattern, as with similar design patterns, may result in unnecessary complexity and extra work in the initial writing of code. Additionally, higher levels of separation and abstraction can result in systems which are more difficult to debug and maintain. Therefore, as in all software designs, the trade-offs must be carefully evaluated.

what’s the difference between a simple factory, a factory method design pattern, and an abstract factory?

Thing that all three have in common is that they are responsible for creating objects.  The calling class (which we call the “client”) wants an object, but wants the factory to create it. I guess if you wanted to sound really professional, you could say that factories are used to encapsulate instantiation.

So what’s the difference between a simple factory, a factory method design pattern, and an abstract factory?

– A Simple factory is normally called by the client via a static method, and returns one of several objects that all inherit/implement the same parent.
– The Factory Method design is really all about a “create” method that is implemented by sub classes.
– Abstract Factory design is about returning a family of related objects to the client.  It normally uses the Factory Method to create the objects.

You can checkout the working project from my git hub repository, here is the link : https://github.com/premaseem/designPatterns/commit/94cdd85ac5f7080fb1be03dc885d6a6dc3b1ad8c#diff-d41d8cd98f00b204e9800998ecf8427e

Let us take a detailed look in each of them with minute details.

Simple Factory
The easiest way for me to remember this is that a simple factory is called directly by the class which wants to create an object (the calling class is referred to as the “client”).  The simple factory returns one of many different classes.  All the classes that a simple factory can return either inherit from the same parent class, or implement the same interface.

simpleFactory

Step One: you call a method in the factory.  Here it makes sense to use a static method.  The parameters for your call tell the factory which class to create.
Step Two:  the factory creates your object. The only thing to note is that of all the objects it can create, the objects have the same parent class, or implement the same interface.
Step Three: factory returns the object, and this is why step two makes sense.  Since the client didn’t know what was going to be returned, the client is expecting a type that matches the parent class /interface.

Please note that this is not an “official” design pattern.

 

Factory Method
The official definition of the pattern is something like: a class which defers instantiation of an object to subclasses.  An important thing to note right away is that when we’re discussing the factory pattern, we’re not concentrating on the implementation of the factory in the client, but instead we’re examining the manner in which objects are being created.
In this example the client doesn’t have a direct reference to the classes that are creating the object, but instead has reference to the abstract “Creator”. (Just because the creator is abstract, doesn’t mean this is the Abstract Factory!).  It is a Factory Method because the children of “Creator” are responsible for implementing the “Create” method. Another key point is that the creator is returning only one object.   The object could be one of several types, but the types all inherit from the same parent class.

factoryMethod

Step One: the client maintains a reference to the abstract Creator, but instantiates it with one of the subclasses.  (i.e. Creator c = new ConcreteCreator1(); )
Step Two: the Creator has an abstract method for creation of an object, which we’ll call “Create”.  It’s an abstract method which all child classes must implement.  This abstract method also stipulates that the type that will be returned is the Parent Class or the Interface of the “product”.
Step Three: the concrete creator creates the concrete object.  In the case of Step One, this would be “Child Class A”.
Step Four: the concrete object is returned to the client.  Note that the client doesn’t really know what the type of the object is, just that it is a child of the parent.

 

Abstract Factory
This is biggest pattern of the three.  I also find that it is difficult to distinguish this pattern from the Factory Method at a casual glance.  For instance, in the Factory Method, didn’t we use an abstract Creator?  Wouldn’t that mean that the Factory Method I showed was a actually an Abstract Factory?  The big difference is that by its own definition, an Abstract Factory is used to create a family of related products (Factory Method creates one product).

AbstractFactory

Step One:  the client maintains a reference to an abstract Factory class, which all Factories must implement.  The abstract Factory is instantiated with a concrete factory.
Step Two: the factory is capable of producing multiple types.  This is where the “family of related products” comes into play.  The objects which can be created still have a parent class or interface that the client knows about, but the key point is there is more than one type of parent.
Step Three: the concrete factory creates the concrete objects.
Step Four: the concrete objects are returned to the client.  Again, the client doesn’t really know what the type of the objects are, just that are a children of the parents.
See those concrete factories?  Notice something vaguely familiar?  There using the Factory Method to create objects.

Spring : Design Patterns Used in Java Spring Framework

Dependency injection/ or IoC (inversion of control) – Is the main principle behind decoupling process that Spring does

Factory – Spring uses factory pattern to create objects of beans using Application Context reference

// Spring uses factory pattern to create instances of the objects
BeanFactory factory = new XmlBeanFactory(new FileSystemResource("spring.xml"));
Triangle triangle = (Triangle) factory.getBean("triangle");
triangle.draw();

Proxy – used heavily in AOP, and remoting.

Singleton – by default, beans defined in spring config file (xml) are only created once. No matter how many calls were made using getBean() method, it will always have only one bean. This is because, by default all beans in spring are singletons.
This can be overridden by using Prototype bean scope.Then spring will create a new bean object for every request.

Model View Controller – The advantage with Spring MVC is that your controllers are POJOs as opposed to being servlets. This makes for easier testing of controllers. One thing to note is that the controller is only required to return a logical view name, and the view selection is left to a separate ViewResolver. This makes it easier to reuse controllers for different view technologies.

Front Controller – Spring provides DispatcherServlet to ensure an incoming request gets dispatched to your controllers.

View Helper – Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.

Template method – used extensively to deal with boilerplate repeated code (such as closing connections cleanly, etc..). For example JdbcTemplate, JmsTemplate, JpaTemplate.

Reference – http://stackoverflow.com/questions/755563/what-are-the-design-patterns-which-used-in-spring-framework