Skip to main content

GOF Design pattern with Java & Real World Examples

What are design patterns? 

So basically these are just collection of best practices to solve recurring problem by different kind of class arrangement. These arrangement could be based on creation of object or structural basis or on basis of required behavior.

Creational Design Pattern

Prototype Design pattern
we will like to use this design pattern whenever creation of initial object & setting required default values is costly. So we just create 1 object & later on whenever more objects required we can provide initial object by just cloning of given object.Java Example is java.lang.Object#clone()

Builder Design Pattern
When we jave object structure are complex and complicated we would go for this.
we will be separating object creation from internal representation. With help of some simple interface we would create complicated Object.

When we need one instance per JVM. Example : Java Run time environment Java.lang.System.  java.lang.StringBuilder, Spring Beans are singleton by default. java.lang.Runtime#getRuntime(). Can be created by Enum & in Java 7 @Singlteon annotation can be used as well.

In factory based on upon input or logic we can create different classes.If we want to create some Room based on Gender.If Boy decorate blue color room if Boy decorate pink color for room. Example in Java is java.util.Calendar#getInstance() 

Abstract Factory
This pattern one level more abstract than factory pattern because it provides interface for creating factory of classes means factory for family of classes. In real we could see an example with Big Brand franchisees where Brand is factory for factory (called franchisee) which produce product for end customer while Main Brand provide all main components or material or practice for other farnchisee. JDK example could be javax.xml.parsers.DocumentBuilderFactory#newInstance() or  javax.xml.xpath.XPathFactory#newInst()

Structural Design Pattern (ABCDFFP)

When we want to decouple an abstraction from its implementation in order that two can vary independently we use bridge pattern.

This pattern let client treat object & group of object in same way.System consist of sub systems & further divided into more sub systems. Its like tree structure as called as part whole hierarchies.
Real World example is Company hierarchy where CEO then GM then AMs then PMs Then Employees. all one under another as tree.

When we connect to proxy object & that proxy object communicate to actual object. real object is not visibile directly to main user. 
Example: java.rmi package, EJB home &

Add functionality or responsibility to object at run time. several type of Pizza can have different type of topping.
So in spite of create classes for all combination we can have pizza as base but applying topping as decorator dynamically.
Example in Java is :
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("a.txt")))
PizzawithCheeseTopping pwct = new PizzawithCheeseTopping(new CheeseTopping( new Pizze()))

FacadeHide complexity of system behind one simple interface.That simple system enable user to access complex systems.
Real world example would be online stores.Where we can just order & payment by few clicks & all other things like order placement, 
payment gateway, Quality check,shipping etc will be managed by it. starting a computer also classic example where before starting computer
checks all of its hardware & software one by one but we initiate is buy just a button push. 

Adapterone common class to match two class. Take input from one class & provide output to other different class.
In Java example  is utility class Arrays.asList(myArray) which take array & output List. In real world example could be converter
which take input as USA electrical points & provide output to Indian appliances.which matches incompatible design as well power output.

Flyweight design patternReuse existing object rather then creating so many object to save cost of creation/memory whenever we 
need lots & lots of object.By reusing same object, calculating extrinsic (storing only intrinsic) attribute do the efficient use of memory. 
Java example is String class String Pool implementation.

Behavioral Design Pattern 

Chain of responsibilityresponsibility is being passed from one object to another object in chain of object until it get finally handled.
In Java Example is Exception Handling &  logger. In real world example could be loan approval or ATM machine.
request is being unaware who is handling & getting passed between complete chain.Sender & requester are decoupled.

This pattern provide access to contents of a collection without exposing its internal structure. It provide a uniform interface for traversing 
different collection. Java example is iterator by which we can iterate almost every java collection without knowing it is arraylist or linked list or
hash set or tree set or any other internal representation. java.util.Scanner,java.util.Enumeration

State when Object behavior change on basis of any appliance follow remote. AC says low temperature compressor on 
or if remote says high temperature compressor off.

State pattern look similar to state but there are differences.                                
difference between State & Strategy
  • The State pattern deals with what (state or type) an object is (in) -- it encapsulates state-dependent behavior, whereas
  • the Strategy pattern deals with how an object performs a certain task -- it encapsulates an algorithm.
Action based on requirement. In Java we have example of Collection.sort(List, Comparator).In this example based on different 
strategy which is we can pass different Comparator. Comparator  is strategy interface we can say. Whatever way we want to sort we 
can pass to collection. sort(). So this collection.sort method or Array.sort() method will behave accordingly.

Observer when we notify to other about changes. As we used to talk about example java example in Java 7 we have class java.util.Observable & 
interface Observer. class need to implement if it want to observe a observable class.All implementations of java.util.EventListener in swing.
In spring also we use event awareness which use observer pattern.

visitor is like adding new action or operation but without changing the classes of the elements on which it operates.we define require functionality 
in a new visitor class. Whichever object  need those action or operation can invoke operations on visitor methods which will perform operation
on object.Without the Visitor Pattern, every time a developer wanted to add a new feature, They would need to add that method to every feature
in the base class.The one actually calls the method of the other and the other executes the desired strategy on it.

Template Method
Some structure is defined which is provided by default while some other things can be changed as per need.
So template method provide default behavior. Any framework we can take as example where structure is being provided a
although we are free to do further implementation as required.

Command pattern
commmand or request encapsulated  as object.command is having all details.real world example is order to restaurant waiter.
Water note down all details then he itself ask chef to prepare dish & then when prepared he take from chef & serve to you.
Java example is java.lang.runnable where we just implement runnable interface, calling start method on thread and it behave like 
thread & do all work needed.

we required to do undo redo operations or commit , rollback operation. we need to store some save points (momento) while doing operations so that momento helps to restore back whenever required.In Jdk implementations,javax.faces.component.StateHolder can help to provide this by saving state.

This helps to reduce communication complexity by providing center point for communication.Real world example is chat application where everyone post & read from chat room only.In java example could be JMS or Enterprise service bus (ESB).

Interpreter pattern helps define a language’s grammar , interpreter uses definition to interpret sentences of that language.
Musician is one example in real world who read nodes & produce same music again. Parser is also an example for interpreter.



Popular posts from this blog

Conversion from Clob To String in java and Vice versa

/***reading Clob data from oracle table and setting to Pojo**/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import oracle.sql.CLOB;


public class MessageDao {
private static String url = "jdbc:oracle:thin:@";
private static String username = "ABC123";
private static String password = "ABC123";

public  List readClobToBO() throws Exception {

Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement stmt = conn
ResultSet resultSet = stmt.executeQuery();
List msgList= new ArrayList();

while ( {

StagedMessage message = new StagedMessage();


Portable Java 8/ JDK8 setup without admin rights

Some time we got machine to work where we don't have access rights to install anything or if you do not want to install. You can get latest jdk running by this trick. Just follow step step & do comment if you like it.

Step by Step details to get running java from .exe setup without any admin rights. Get portable 7 zip from portableapps.comdownload java 8 from oracle 7 zip & extract jdk-8u102-windows-x64.exeyou will see below folders                .data                .pdata                .rdata                .reloc                .rsrc                .text                CERTIFICATE

          5.Go inside E:\jdk-8u102-windows-x64\.rsrc\1033\JAVA_CAB10you will find 111 file.

         6.extract it it some folder where you can find again extract that to some folder say Java & copy it to very first folder of setup along with .data,.rsrc etc.
         7.Go to folder where you have co…