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.
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()
As per GOF:-
“Decouple an abstraction from its implementation so that the two can vary independently”
“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.
- 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)
- 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"));
- 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.
- 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.
Next part - Behavioral Design Pattern is under progress