Sunday 30 March 2014

Java Design Patterns Part - 2

Design Pattern In Java

Hibernate                                                                                       Core Java

Structural : This design patterns describes how classes and objects can be composed, to form larger structures. These patterns teaches us about how the classes inherit from each other and how they are composed from other classes.This patterns simplifies the structure by identifying the relationships.

  1. Adapter This pattern work as a connector or helps to join two unrelated interfaces so that they can work together.
For example :
A well defined example for Adapter design pattern is Laptop charger. When we are using our laptop then to charge the laptop battery we are connecting this to mainline socket but using adapter in between. Because normally laptop requires least voltage(20 V) in order to charge its battery and mainline is supplying more voltage(240 V). So we need a power adapter which converts and provide the required voltage in order to charge the Laptop battery. This pattern combines the capability of two independent interfaces.The Adapter pattern which is a Structural Design pattern can be used to realize relationship between entities. This pattern can be implemented in two ways, either by Inheritance(is-a)or by Composition(has-a).

The description given by Gof(Gang of four)about this pattern is below:
"Convert the interface of class into another interface clients expect.Adapter lets class work together that couldn't otherwise because of incompatible interfaces".
Examples as per java API :
  • java.util.Arrays#asList()
  • java.io.InputStreamReader(InputStream) (returns a Reader)
  • java.io.OutputStreamWriter(OutputStream) (returns a Writer)
  • javax.xml.bind.annotation.adapters.XmlAdapter#marshal() and #unmarshal()
    1. Bridge The Bridge pattern is known as Structural pattern and GOF states that pattern tells that :
As per GOF:-
Decouple an abstraction from its implementation so that the two can vary independently”

Mainly this pattern is useful in graphic toolkits that needs to run on a variety of platforms. The display of various image formats on different OS is the best example of the Bridge pattern. The image structure is the same across all OS, but how they are viewed (the implementation) is different on each OS. This is the type of decoupling that the Bridge pattern allows. This pattern allows us to separate the abstraction and the implementation. It means to say that this pattern allows the Abstraction and the Implementation to be developed independently.This layer provides a two layer of abstraction. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

For example:
The example of TV and Remote Control(typo in diagram) can demonstrate the two layers of abstraction. We have an interface for TV and an abstract class for remote control. It is not a good idea to make a concrete class for either of them, because other vendors may make different implementations.
  • This creates 2 hierarchies i.e. One for abstraction and another for implementation.
  • This avoids permanent binding by removing the dependency between abstraction & Implementation.
  • It should be used when we need to switch between the various implementations.
  • Client should not be impacted if there is any modification in abstraction implementation.
  • Abstraction and Implementation can be extended separately.
  • When we are dealing with multiple implementations then we can use Bridge Design Pattern.
  • Bridge will coordinates between Abstraction and Implementation.
Example as per java API : Object Persistence API is the example of Bridge Design pattern.
A classic example of Bridge is Drivers. Each driver is an instance of the Adapter pattern, providing the interface a client expects, using the services of a class with a different interface. An overall design that uses drivers is an instance of Bridge. The JDBC architecture decouples an abstraction from its implementation so that the two can vary independently—an excellent example of Bridge e.g. JDBC ODBC Bridge driver.
    1. Composite This design pattern is represents as a partitioning design pattern. This pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The purpose of composite is to "compose" objects into tree structures to represent part-whole hierarchies.
As per Gof:-
"Compose objects into tree structure to represent part-whole hierarchies.Composite lets client treat individual objects and compositions of objects uniformly".

Questions : What is the meaning of part-whole hierarchies?
Answer:- A system is a combination of subsystem or components. Components are the combinations of smaller components. Similarly, Smaller components are the combination of smaller elements. This is known as part-whole hierarchy.

This design pattern allows as to have a tree structure and each node of that tree structure will perform a specific task.
Real World example : We can think about our company. There are Project Director, Project Director will further categorized into Project managers, Project managers can be further divided into Project leads, then Project lead can have many Team leads, then Team leads may have many Developers.
This is making a tree structure and composing an organization and each node of this tree structure is performing some task for that they are getting salary.

Example as per API : - Tiles framework in Struts, which help us to compose a webpage using multiple JSP pages. This is actually an implementation of CompositeView Pattern and this pattern itself based on Composite pattern.

Another example as per Java API :-
java.awt.Container#add(Component) (In awt, we have containers and components, the best example for Composite pattern)
javax.faces.component.UIComponent#getChildren() (In JSF UI)
    1. Decorater – Decorater design pattern is used to change or extend the behavior of an object. This is used to attach or add responsibities to an individual object dynamically, without affecting the behavior of other objects from the same class. Alternatively this is also known as Wrapper. In different words, this pattern uses composition instead of inheritance to extend the functionality of an object at runtime.
When to use decorator design pattern?
Answer :- we can use this design pattern when :
When we need to attach responsibilities to individual objects dynamically without affecting other objects.
For adding the beviour which can be withdrawn in future.
Extending functionality by sub-classing is no longer possible.
Decorators are very flexible alternative of inheritance.

Example in java API :-
[I] In Java Collection API, the checkedXXX(), synchronizedXXX() and unmodifiableXXX() methods.
e.g. checkedCollection(), checkedSet(), checkedSortedSet(), checkedList(), checkedMap(), checkedSortedMap() are the examples of decorator design pattern.

[II] javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper.

[III] All subclasses of java.io.InputStream, OutputStream, Reader and Writer constructors because
These classes are abstract since in that way they can be easily extended and the implementor classes could use the Decorator Pattern. With the decorator pattern, the implementor class can add dynamic functionality at runtime. For example: we can have an InputStream which will read a File using FileInputStream or it can also be read serialized objects using ObjectInputStream.

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("/project/resources/test.dat"));
    1. Facade A facade is generally the face of a building, especially the principal face. This word comes from the French Language, which means frontage or face. During a building creation it is having many complexities like boring, wiring, pipelining or others, but we are seeing only the frontface of the building because it hides all the complexities.
This is the way we can use Facade design pattern. This pattern provides a simplified interface to a set of interfaces within the system and thus it hides the complexities of the subsystem from the client.

As per GoF:- definition facade design pattern is, “Provide a unified interface to a set of interfaces in a subsystem. Facade Pattern defines a higher-level interface that makes the subsystem easier to use.”
We can use Facade design pattern for :-
  • It will increase the readability.
  • Easy to maintain.
  • Makes a library easier to use, understand and test because the facade will provide convenient methods for common tasks.
  • It reduces the dependencies of the external code, so it provides flexibility.
  • We can use this pattern to collate all the complex method calls and related code blocks and channelizes it through one single Facade class. In this way with respect to client there is only one single call. Even if we make changes to the subsystem classes and then there is no impact to the client call which means this increases loose coupling.
Example :- Service oriented architectures make use of the facade pattern. For example, in web services, one web service might provide access to a number of smaller services that have been hidden from the caller by the facade. Like while purchasing clothes online how it is interacting through payment gateway that complexities if unknown by the user.

Facade design pattern used in java api are : -
javax.servlet.http.HttpSession
javax.servlet.http.HttpServletRequest
javax.servlet.http.HttpServletResponse
javax.faces.context.ExternalContext
javax.faces.context.FacesContext, it internally uses many others the abstract/interface types like LifeCycle, ViewHandler, NavigationHandler and many more without showing that to enduser.
  1. Flyweight – It is a kind of design pattern which is used to reduce the creation of multiple objects which are identical in nature. This design pattern is used when there is requirement to create large number of objects which are similar in nature. It helps to minimizes the memory use by sharing as much data as possible in case of similar objects. As we know creation of multiple objects consumes huge memory so this design pattern is providing a solution to minimizes the amount of memory by sharing those objects or we can say that this pattern allow us to reuse memory spaces within the application when we have huge number of objects which are almost same in nature. Sharing is the key feature of this design pattern.
As per GOF : "Facilitates the reuse of many fine grained objects, making the utilization of large numbers of objects more efficient."

For example : Suppose we are making a game for Android OS like car race app, then the shape of car we can share by providing different colours to those cars and making them different cars for the game players.
When we think about this pattern then we need to think about the concept of Intrinsic and Extrinsic state, The data which comes inIntrinsic state are constant, so they can be stored in memory. But the data which comes under Extrinsic state are not constant, they are required to be calculated on the fly or dynamically, so the reason they can't be stored in memory. So as per the above example, we can consider as the shape of each car will be under Intrinsic state andthe color of each car will be in Extrinsic state.

In Java API : String Pool implementation is the best example of Flyweight Design Pattern.
Other example are : java.lang.Integer#valueOf(int) (also on Boolean, Byte, Character, Short and Long)

    7) Proxy : The word Proxy means an agent or substitute which is authorized to act for another one. In the design pattern Proxy will represent another object.
As per GOF :- "Provide a surrogate or placeholder for another object to control access over it."

This pattern is also known as surrogate or placeholder. This pattern allows us to create a wrapper class over the actual object. Here wrapper class which acts as proxy helps to control access to real object so in turn we can add extra functionalities to real object without changing real object's.

For example: In most of the IT companies, they are allowing the internet use but blocking the sites like Gmail, Yahoo, Facebbok by using a Proxy server which acts as a wrapper of original server.

Example as per java API : java.lang.reflect.Proxy, java.rmi.*.
If we are working with Spring, then also we can find AOP proxies object.

We can use proxy design pattern in below conditions:

[1] During the need of a remote proxy which provides a local representative for an object in a different address space by providing interface for remote resources such as web service or REST resources.

[2] During the need of a virtual proxy which creates expensive object on demand.

[3] During the need of a protection proxy which controls access to the original object. Protection proxies are useful when objects should have different access rights.

[4] During the need of a smart reference which is a replacement for a bare pointer that performs additional actions when an object is accessed.

[5] Suppose there is a requirement to add a thread-safe feature to an existing class without changing the existing class's code.

Java-Collections                                           Spring-Core                                                     JSON

Next part - Behavioral Design Pattern is under progress

Friday 14 March 2014

Java Design Patterns Part - 1

Design Pattern In Java

Web Service                                                                                              Java and It's Version - Features

Question:- What is design pattern?

Answer:- As per GOF(Gang of Four), "Design Patterns: Elements of Reusable Object-Oriented Software"

It help to provide solutions to common software design problems. Its a kind of a powerful tool for software development. Its an independent strategies for solving common object-oriented design problems. It explains a general design that addresses a recurring design problem in object-oriented systems.Design pattern is nothing but a general resuable solution to commonly occurring problem within the given context in software design.

History of software patterns :-
  • 1987 – Ward Cunningham and Kent Beck used Alexander's ideas to develop a small pattern language.
  • 1990 – The Gang of Four ( Erich Gamma, Richard Helm, Ralph Johnson & John Vlissides) begin work compiling a catalog of design patterns.
  • 1991 – Bruce Anderson gives first patterns Workshop at OOPSLA
  • 1993 – Kent Beck and Grady Booch sponsor the first meeting – what is now known as Hillside group
  • 1995 – The Gang of Four published the design pattern book.
  • 2002 – Martin Fowler published the book “Patterns of Enterprise Application Architecture”.

Advantage of Design pattern
  • Reusable in nature.
  • Provide the solution that help to define the system architecture
  • Provide transparency towards application design
  • Easily maintenable
  • Reducing complexity by providing the clarity towards the system architecture

Design patterns is mainly categorized in three parts.
  • Creational : - It concerns the process of object creation
  • Structural :- This deals with the composition of classes & objects.
  • Behavioral :- This Characterize the ways in which classes/objects interact and distribute responsibility.
Creational

1) Singleton- Only one instance of the class :- This design pattern is recognized by creational methods returning the same instance everytime.

For example :

a) java.lang.Runtime#getRuntime()
b) java.awt.Desktop#getDesktop()

2) Abstract Factory: An abstract factory to produce factory of objects. This design pattern is having one level of abstraction higher than factory design pattern. This pattern returns the factory of classes. In case of factory pattern, it returns object of one of the subclass in several subclasses and this(Abstract factory) design pattern will return factory which later will return one of the sub classes. This design pattern is recognized by creational methods returning the factory itself which in turn can be used to create another abstract/interface type. Finally we can tell that this design pattern create factory which later creates products.

a) javax.xml.parsers.DocumentBuilderFactory#newInstance()
b) javax.xml.xpath.XPathFactory#newInstance()
c) javax.xml.transform.TransformerFactory#newInstance()

For example : 

 DocumentBuilderFactory is the best example of Abstract design pattern which creates a factory which is DocumentBuilder which later help us to create Document objects. Here we can find that DocumentBuilderFactory is the AbstractFactory where as DocumentBuilder is the Factory and Document is the Product.

DocumentBuilderFactory docBuildAbstractFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuildFactory = docBuildAbstractFactory.newDocumentBuilder();
Document doc = docBuildFactory.newDocument();

3)Factory A factory that produces objects. This design pattern is used to create instance of our classes which is somehow similar in features. For example :- If we will take “Human” class and want to create objects of “man” and “woman” classes dynamically which is subclass of human then we can go with this design pattern because man & woman classes are somehow similar to human class in terms of features.This design pattern is recognized by creational methods returning an implementation of an abstract/interface type. Finally we can tell that this design pattern creates products instead of factory.

a) java.text.NumberFormat#getInstance()
b) java.util.Calendar#getInstance()
c) java.nio.charset.Charset#forName()
d) java.util.ResourceBundle#getBundle()
e) java.net.URLStreamHandlerFactory#createURLStreamHandler(String) (Returns singleton object per protocol)

Difference between AbstractFactory & Factory design pattern

[I] AbstractFactory uses compositionto delegate responsibility of creating object to another class while Factory pattern uses inheritanceand relies on derived classes or sub classes for object creation.

[II] AbstractFactory creates Factory which later creates objects of their sub classes where as Factory creates products instead of factory.

4) Builder :-Its a pattern used to construct a complex object in step by step process and at last or final step will return the object. These separates the construcution of complex objects from their representation. It is recognized by creational methods returning the instance itself. 

For example :

a) java.lang.StringBuffer#append()
b) java.lang.StringBuilder#append()
c) java.nio.ByteBuffer#put() (also on IntBuffer, CharBuffer, ShortBuffer, LongBuffer, FloatBuffer and DoubleBuffer)
d) All implementations of java.lang.Appendable

According to Gang of Four(Gof):- The Builder Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations.For example, we can think for making of a Mobile Handset. Making of a cellphone involves various steps such as embedding the processor chip, Ram, camera, screen, and supporting softwares. Finally we will get a complete Mobile phone object nothing but a complex object obtained by going through step by step process. With the help of the same process, we can make cellphones having different features.

Question:- When to use Builder design pattern?
Answer :- This design pattern is useful when we need to do lots of things to build an object. 

For example : 

In the creation of DOM object, we have to create plenty of nodes and attributes to get our final object.

    5) Prototype Prototype meaning itself is telling that making a clone. Prototype design pattern is used when an application needs to create many instances of a class, which is almost same as original one. So this we can do using clone. If the object creation is a expensive process then we can clone that object. While appling cloning, we should know which cloning we have to use Shallow or Deep cloning

    For example:-
      a) java.lang.Object#clone() (the class has to implement java.lang.Cloneable)