Wednesday, December 13, 2017

Visitor Pattern


Definition -

    Allows one or more operations to be applied at run time allowing the operations to be decided at runtime rather than compile time.


Scenario -
   
    Let us take the same example of a car customization plant where you can customize the windshield color, wheel, color, stripes.
1) We will have an interface called customizable which will be implemented by the components which can be customized based on the users wish else it will use the default. The following things can be customized - windshield color, stripes, wheel.

package VisitorPattern;

public interface customizable {
    
    public void addtocar(customizer c);

}

2) We will have concrete classes for the same windshieldcolor, stripes, wheel.
windshield.java

package VisitorPattern;

public class windowshield implements customizable{
    
    String color;
    
    public windowshield(String color) {
        this.color=color;
    }

    @Override
    public void addtocar(customizer c) {
        
        c.addcomponent(this);
        
    }
    

}

stripes.java
package VisitorPattern;

public class stripes implements customizable{
    
    String stripestyle;
    
    public stripes(String stripestyle) {
        this.stripestyle=stripestyle;
    }

    @Override
    public void addtocar(customizer c) {
        
        c.addcomponent(this);
        
    }
    
    

}

wheel.java

package VisitorPattern;

public class wheel implements customizable {

    String style;
    
    public wheel(String style) {
        this.style=style;
    }
    
    @Override
    public void addtocar(customizer c) {
        
        c.addcomponent(this);
        
    }

}

3) We will have a component called customizer which will be an interface and will have the call to all the customizable components. The interface will enable us to extend in future and be used as a standard across different types of vehicles in future.
package VisitorPattern;

public interface customizer {
    
    public void addcomponent(windowshield w);
    public void addcomponent(wheel wl);
    public void addcomponent(stripes s);

}

4) We will have implementer which is a concrete implementation of the customizer.

package VisitorPattern;

public class customizerimpl implements customizer {
    
    

    @Override
    public void addcomponent(windowshield w) {
        
        System.out.println("Adding windshield of color: "+w.color);
        
    }

    @Override
    public void addcomponent(wheel wl) {
        
        System.out.println("Adding wheel of style: "+wl.style);
        
    }

    @Override
    public void addcomponent(stripes s) {
        
        System.out.println("Adding stripes of style: "+s.stripestyle);
        
    }

}


To see this pattern in action use the code below - 
package VisitorPattern;

import java.util.ArrayList;

public class visitordemo {

    public static void main(String[] args) {
        
        ArrayList<customizable> customcomp=new ArrayList<customizable>();
        customcomp.add(new windowshield("Blue"));
        customcomp.add(new wheel("Yokohama Pro ++"));
        customcomp.add(new stripes("Stripe1"));
        
        customizer creator=new customizerimpl();
        
        for(customizable tempc: customcomp) {
            tempc.addtocar(creator);
        }

    }

}



Place to use -
1) When you want to call different functionalities based on user input and it might be unrelated objects which might be passed based on scenario.

The code for the above is present in the
link

Template Pattern


Definition -

    As the name states, this pattern will provide a template of steps to be followed inorder to complete a task or part of a task.

There will be an interface or an abstract class which will be used by concrete classes and implement or extend all the steps.
Scenario -
   
    Let us take the same example of a car manufacturing plant where in the plant manufactures a car or sedan. The process to build either car is the same hence -
1) We will have an abstract class called buildcar with the following functions - getchassis, addwheel, addengine, addseats. 

package TemplatePattern;

public abstract class buildcar {
    
    public abstract void getchassis();
    public abstract void addengine();
    public abstract void addwheels();
    
    public final void build() {
        getchassis();
        addengine();
        addwheels();
        System.out.println("Completed building");
    }

}


2) We will have two concrete classes called hatchback and sedan.
hatchback.java

 
package TemplatePattern;

public class hatchback extends buildcar {

    @Override
    public void getchassis() {
        
        System.out.println("Getting chassis for a hatchback");
        
    }

    @Override
    public void addengine() {
        
        System.out.println("Adding engine to hatchback");
        
    }

    @Override
    public void addwheels() {
        
        System.out.println("Adding wheels to hatchback");
        
    }

}

sedan.java
 
package TemplatePattern;

public class sedan extends buildcar {

    @Override
    public void getchassis() {
        
        System.out.println("Getting chassis for a sedan");
        
    }

    @Override
    public void addengine() {
        
        System.out.println("Adding engine to sedan");
        
    }

    @Override
    public void addwheels() {

        System.out.println("Adding wheels to sedan");
        
    }

}

3) The below code shows the demo for the same
package TemplatePattern;

public class templatedemo {

    public static void main(String[] args) {
        
        buildcar bc=new hatchback();
        bc.build();
        

    }

}


Place to use -
1) When have a scenario which can be made into templates.
2) You want to control what happens at each step and avoid rewriting the code in multiple places.


The code used above is present in the link

Strategy Pattern

Definition -

    This is a pattern where in the client can choose among the options available to perform a specific task.
   
Scenario -
   
    Lets take a scenario where in you want the user to login via either forms authentication or google or facebook id. In this case you can apply the strategy pattern where in the same task of authentication is done but the method by which the authentication is done is different.
   
Based on the above -
1) We will have an interface called iauthenticate with a function called authenticateuser.

package StrategyPattern;

public interface iauthenticate {
    
    
    public boolean authenticateuser();

}

2) We will have two concrete classes called formsauthentication and googleauthentication.
formsauthentication.java
 
package StrategyPattern;

public class formsauth implements iauthenticate{

    String user;
    String password;
    
    public formsauth(String usr, String pwd) {
        this.user=usr;
        this.password=pwd;
    }
    
    @Override
    public boolean authenticateuser() {
        String pwd=getauthdetails(this.user);
        if(pwd==this.password) {
            return true;
        }
        else {
            return false;
        }
        
    }

    
    public String getauthdetails(String user) {
        
        return "*******";
        
    }

}


googleauthentication.java
package StrategyPattern;

public class googleauthentication implements iauthenticate {

    
    String user;
    String token;
    
    public googleauthentication(String usr,String tkn) {
        this.user=usr;
        this.token=tkn;
    }
    
    public String getauthdetails(String user) {
        //get the token from google
        return "axr4550313djrldoepcvjrmvrortjvlr";
    }

    @Override
    public boolean authenticateuser() {
        String temptkn=getauthdetails(this.user);
        if(this.token==temptkn) {
            return true;
        }
        return false;
    }

}



3) We will have a class called strategydemo which will have the option chosen by the user to authenticate and gain access into the system.
 
package StrategyPattern;

public class Strategydemo {
    
    public static void main(String args[]) {
        
        iauthenticate ia=null;
        String authtype="forms";
        
        if(authtype.equalsIgnoreCase("forms")) {
            ia=new formsauth("user1","*******");
        }else if(authtype.equalsIgnoreCase("Google")) {
            ia=new googleauthentication("user1","axr4550313djrldoepcvjrmvrortjvlr");
        }
        
        if(ia.authenticateuser()) {
            System.out.println("Authentication successful");
        }
        
    }

}



Place to use -
1) When you want to choose a technique to perform a functionality but you want to provide flexibility in terms how this can be achieved.


The code used above is present in the link here

State Pattern

Definition -

    This is a pattern where in the object changes its behavior based on the state.
   
Scenario -
Let us consider a scenario where in the windshield of your car has to start the wiper if the rain starts or it needs to enable polarized light depending on the intensity of light.

Based on the above -
1) A interface called eventstate which will have a method called performaction.

package StatePattern;

public interface eventstate {
    
    public void performaction();

}

2) A class rain which will implement the eventstate.
package StatePattern;

public class rain implements eventstate {

    @Override
    public void performaction() {
        
        System.out.println("Wiper will be turned on");
        
    }

}

3) A class day which will implement the eventstate.
package StatePattern;

public class day implements eventstate {

    @Override
    public void performaction() {
        
        System.out.println("Wiper will be turned on");
        
    }

}

4) A windshieldcontext which will perform action based on state.
package StatePattern;

public class windshieldcontext implements eventstate {
    
    eventstate es;
    
    public void setcontext(eventstate e) {
        this.es=e;
    }

    @Override
    public void performaction() {
        
        this.es.performaction();
        
    }

}

5) The client code for the same is given below


package StatePattern;

public class statedemo {
    
    public static void main(String args[]) {
        eventstate es;
        windshieldcontext ws=new windshieldcontext();
        String states="Rain";
        if(states.equalsIgnoreCase("Rain")) {
            es=new rain();
            ws.setcontext(es);
        }
        else if(states.equalsIgnoreCase("Day")) {
            es=new day();
            ws.setcontext(es);
        }
        
        ws.performaction();
        
    }

}

Place to use -
1) When you have want the object to behave different in different scenarios and at the sametime decouple the systems so that the conditions are decided only in run time and not in compile time.

The code for the above is present in the link
here

Observer Pattern

Definition -

    It provides a proxy implementation for another object and controls access to the real object.

These are patterns which you would be using unknowingly (if you are new to design patterns) in the click event listener or the event listeners.
Scenario -

1) Let us have a class called obsrvvalue which will have a variable whose value is being observed. This is called observable.

package ObserverPattern;

import java.util.Observable;

public class obsrvvalue extends Observable {
    
    private int val=0;
    
    public obsrvvalue(int newval) {
        this.val=newval;
    }
    
    public void setnewval(int newval) {
        this.val=newval;
        setChanged();
        notifyObservers();
    }
    
    

}

2) Let us have a class called observerobject which will observe the observable object and check if the value is same or not and report.
package ObserverPattern;

import java.util.Observable;
import java.util.Observer;

public class observerobject implements Observer{
    
    
    private obsrvvalue obs=null;
    
    public observerobject(obsrvvalue o) {
        this.obs=o;
    }

    @Override
    public void update(Observable arg0, Object arg1) {
        if(arg0==arg1) {
            System.out.println("Both are equal");
        }
        else {
            System.out.println("The value is updated");
        }
        
    }

}

3) To see the pattern in demo use the code below

package ObserverPattern;

public class observerdemo {
    
    public static void main(String args[]) {
        
        obsrvvalue o=new obsrvvalue(10);
        observerobject oo= new observerobject(o);
        o.addObserver(oo);
        o.setnewval(10);
    }

}

Place to use -
1) When you have listener waiting to act if the object changes.


The code for the above is present in the link here

Memento Pattern

Definition -

    This pattern provides ability to make efficient use of resources when there are too many objects created by reusing some or all of them.
   
Scenario -

    The most common example and the best suited that example you will see for this is a file editor where in the file gets saved after sometime and if the system shuts down unexpectedly on restart the system will give you an option to recover a saved state. This is one of the best example you can get for this.
Based on the above -
1) There will be a class filesavedstate which will server memory of the previously automated saved state.

package Memento;

public class filesavedstate {
    private String data;
    
    public filesavedstate(String state) {
        this.data=state;
    }
    
    public String getdata() {
        return this.data;
    }

}

2) There will be a class called file which will be modified by a program and saves its state into the filesavedstate class and obtains it if necessary.
package Memento;

public class file {
    
    public String filedata;
    filesavedstate fs;
    public file(String content) {
        this.filedata=content;
    }
    
    public void savestate() {
        fs=new filesavedstate(this.filedata);
    }
    
    public void getsaveddata() {
        String saveddata=fs.getdata();
        System.out.println("The saved data is :"+saveddata);
    }
    

    public static void main(String[] args) {
        
        file f=new file("Trying to show a demo");
        f.savestate();
        f.getsaveddata();
    }

}


Place to use -
1) When you want to save a state of the object and use it for later.
2) Useful in editors.


The code for the above can be found in the link here

Mediator Pattern

Definition -

    This provides the ability to have effective communication between two modules or objects within the same module. This provides centralized control over the system.

Scenario -

    Let us take an example of an object wanting to write into a filesystem. In this case we will have a mediator to which all the objects will communicate and write into the file.
Based on the above scenario -
1) filemediatorinterface class who provides the implmentation guidelines 

package MediatorPattern;

public interface ifilemediator {
    
    public void addrequest(filemod f);
    
    public void addfile(File f);
    
    public void givecontrol(File f, filemod fm);
    

}

2) A filemod class which wants to modify a file.
package MediatorPattern;

public class filemod {
    
    String modname;
    File filename;
    
    public filemod(String name, File file) {
        this.modname=name;
        this.filename=file;
    }
    
    public void modifyfile(File f) {
        System.out.println("Modifying file : "+f.filename);
    }

}

3) A File class which is the one to be modified.
package MediatorPattern;

public class File {
    
    public String filename;
    
    public File(String name) {
        this.filename=name;
    }
    

}

4) A filemediator which controls which object gets to perform action.
package MediatorPattern;

import java.util.ArrayList;

public class filemediatorImpl implements ifilemediator{
    
    ArrayList<filemod> fm=new ArrayList<filemod>();
    
    ArrayList<File> f=new ArrayList<File>();
    

    @Override
    public void addrequest(filemod f) {
        
        System.out.println("Adding request :"+f.modname+ " into the queue");
        fm.add(f);
        
    }

    @Override
    public void givecontrol(File f, filemod fm) {
        
        System.out.println("Giving control to filemod "+fm.modname+" over the file "+f.filename);
        fm.modifyfile(f);
        
    }

    @Override
    public void addfile(File f) {
        
        System.out.println("Fetching file "+f.filename+ " for modification");
        
    }

}



Place to use -
1) When you have too many objects from a system speaking too many objects of other system.
2) You have very structured communication channel


The code for the above is present in the link here

Interpreter Pattern

Definition -

    The use of an interpreter that used to interpret the requests from the client through the use of representations.

Scenario -

    Let us take an example of currency conversion where in a client wants to convert money from USD to either INR or Euros. The system uses the conversion factor to calculate the amount and send it back to the client.
   
   
Based on the above scenario -
1) An interpreter called currencyconverter.

package InterpretorPattern;

public class currencyconvertor {
    
    double cusdtoinr=60.0;
    double cusdtoeur=1.3;
    
    public double getusdtoinr(double sourceamount) {
        return sourceamount*cusdtoinr;
    }
    
    public double getusdtoeur(double sourceamount) {
        return sourceamount * cusdtoeur;
    }

}

2) A class which will have the actual interpretation called convertor.
<pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>package InterpretorPattern;

public interface convertor {
    
    double convert(currencyconvertor cc);

}

</code></pre>

3) A class called USDtoINR and another called USDtoEur

usdtoeurjava
package InterpretorPattern;

public class usdtoeur implements convertor {
    
    private double amt;
    
    public usdtoeur(double curr) {
        this.amt=curr;
    }

    @Override
    public double convert(currencyconvertor cc) {
        return cc.getusdtoeur(amt);
    }

}


usdtoinr.java
 
package InterpretorPattern;

public class usdtoinr implements convertor{

    private double amt;
    
    public usdtoinr(double curr) {
        this.amt=curr;
    }
    
    @Override
    public double convert(currencyconvertor cc) {
        return cc.getusdtoinr(amt);
    }

}



4) A client which will use the interpreter to covert the value.
package InterpretorPattern;

public class interpretordemo {
    
    
    
    
    public static void main(String args[]) {
        
        System.out.println("Converting $100 to EUR");
        double amt=100;
        double convertedamt=0;
        currencyconvertor cc=new currencyconvertor();    
        String converttocurr="EUR";
        
        convertor c=null;
        
        if(converttocurr.equalsIgnoreCase("INR")) {
            
            c=new usdtoinr(amt);
            convertedamt=c.convert(cc);
            System.out.println("The converted amount in INR is: "+convertedamt);
            
        } else {
            
            c=new usdtoeur(amt);
            convertedamt=c.convert(cc);
            System.out.println("The converted amount in EUR is: "+convertedamt);
            
        }
        
        
    }
    
    
    
    

}



Place to use -
1) It can be used in places where you want one format to be converted into another format.
2) It can be used in places where you are checking for grammar or evaluating an expression written on an UI.


To be careful about -
1) Performance of the code can be an issue, so you need to use this pattern very carefully.


The link for the code is present in the link here

Command Pattern

Definition -
    It provides a generic interface to all the classes which implement it to execute certain commands. This can be treated like the director in the builder pattern.


Scenario -

    Let us take an example of the production line itself, where the client places an order for a vehicle and depending on the order a hatchback or a sedan car is created.
In this case -
1. The interface called order which have an execute funtion to process the request of the client. Note, we can name the function with any name, for the sake of understanding it has named as execute.

 
package CommandPattern;

public interface order {
    
    public void execute();

}

2. hatchback is a class which will implement order and create a hatchback.
 
package CommandPattern;

public class hatchback implements order {

    @Override
    public void execute() {
        
        System.out.println("Creating a hatchback");
        
    }

}

3. sedan is a class which will implement order and create a sedan.
package CommandPattern;

public class sedan implements order {

    @Override
    public void execute() {
        
        System.out.println("Creating a sedan");
        
    }

}

4. A class called router which will hold the order object and invokes the method.
package CommandPattern;

public class router {
    
    String typeofcar=null;
    order o=null;
    
    
    
    public void createcar(String type) {
        if(type.equalsIgnoreCase("Hatchback")) {
            o=new hatchback();
        }else if(type.equalsIgnoreCase("Sedan")) {
            o=new sedan();
        }
        
        o.execute();
    }
    
}

5. Client class which will order for a hatchback or a sedan.
   
package CommandPattern;

public class commandpattern {
    
    public static void main(String args[]) {
        
        router r=new router();
        r.createcar("Hatchback");
        r.createcar("Sedan");
        
        
    }

}




Place to use -
1) When you want the client and the implmentor to be independent of each other.
2) When the request processor need not be known to the client during compile time.
3) One interface to do varying operations based on varying commands at varying time.

Place not to use -
1) Can create maintainence nightmare because if the system has lot of commands then it can cause confusions.
2) If the command parameters vary in future then it can cause change in the entire implementation.

The link for the code above is in the link here

Chain of Responsibility Pattern

Definition -
    This is a pattern where in there are a series of handlers which cater to a specific part or order of the request. In this pattern the client will not know who is addressing the request. The handlers decide among themselves who will server a particular request.
    This can also result in none of the handlers serving the request.


Scenario -
Lets take an example of a warehouse machine whose job is sort the incoming materials based on the type. For simplicity lets take there are two types of containers with tags of solid and liquid.
In this we will have a
1. The object here is a package so we will declare a class called pckg. 
 
package ChainofCommandPattern;

public class pckg {
    
    String type;
    
    public pckg(String objtype) {
        this.type=objtype;
    }
    
    public String gettype() {
        return this.type;
    }

}


2. A packagehandler which will have the functions that needs to be implemented. 
 
package ChainofCommandPattern;

public interface packagehandler {
    
    void setnext(packagehandler ph);
    void handlerequest(pckg pkg);

}

3. A solidpackagehandler and liquidpackagehandler which will have respective functions to handle the package.
solidpackagehandler.java
 
package ChainofCommandPattern;

public class solidpackagehandler implements packagehandler {

    packagehandler next;
    
    @Override
    public void setnext(packagehandler ph) {
        
        next=ph;
        
    }

    @Override
    public void handlerequest(pckg pkg) {
        
        if(pkg.type.equalsIgnoreCase("Solid")) {
            
            System.out.println("Handled the Solid object");
            
        } else if(pkg.type.equalsIgnoreCase("Liquid")) {
            next.handlerequest(pkg);
        }
        
    }

}


liquidpackagehandler.java

package ChainofCommandPattern;

public class liquidpackagehandler implements packagehandler{
    
    packagehandler next;

    @Override
    public void setnext(packagehandler ph) {
        
        next=ph;
        
    }

    @Override
    public void handlerequest(pckg pkg) {
        
        if(pkg.type.equalsIgnoreCase("Liquid")) {
            
            System.out.println("Handled the Liquid object");
            
        } else if(pkg.type.equalsIgnoreCase("Solid")) {
            next.handlerequest(pkg);
        }
        
    }
    
    

}


4. Finally a client which will use the above classes.
package ChainofCommandPattern;

public class chainofcommandclient {
    
    public static void main(String args[]) {
        
        packagehandler pckg1=new solidpackagehandler();
        packagehandler pckg2=new liquidpackagehandler();
        
        pckg1.setnext(pckg2);
        
        pckg1.handlerequest(new pckg("Solid"));
        pckg2.handlerequest(new pckg("Liquid"));
        
    }

}

   

Place to use -
1. When you have multiple handlers which can process the same request.
2. A request not being handled by any handler is an accepted scenario.



Place not to use -
1. Can be slower since it has to follow a specified path.
2. A request might not be addressed by the system implementing this pattern.
3. It can be difficult to maintain if the system has too many handlers and complex routes.



Monday, December 11, 2017

Proxy Pattern

Definition -

    It provides a proxy implementation for another object and controls access to the real object.
   
Scenario -

    let us consider an example of Manufacturing of a car in a plant which produces a hatchback and a sedan.
based on the above scenario -
1) We will have an interface called car.

package ProxyPattern;

public interface car {
    
    public void manufacture();

}

2) We will have concrete classes called hatchback and sedan
hatchback.java
 
public class hatchback implements car {

    @Override
    public void manufacture() {
        
        System.out.println("Manufacturing a hatchback");
        
    }

}

sedan.java

package ProxyPattern;

public class sedan implements car {

    @Override
    public void manufacture() {
        
        System.out.println("Manufacturing a sedan");
        
    }

}

3) We will have an handler called carhandler which will be responsible for invoking the classes based on request.
package ProxyPattern;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class carhandler implements InvocationHandler {
    
    public Object realcar=null;
    
    public carhandler(Object realcar) {
        this.realcar=realcar;
    }
    

    @Override
    public Object invoke(Object duplicate, Method arg1, Object[] arg2) throws Throwable {
        
        Object temp=arg1.invoke(realcar, arg2);
        return temp;
    }

}


4) To see the pattern in action use the code below - 
package ProxyPattern;

import java.lang.reflect.Proxy;

public class proxydemo {

    public static void main(String[] args) {
        
        
        car ht=new hatchback();
        carhandler ch=new carhandler(ht);
        car duplicate = (car) Proxy.newProxyInstance(ht.getClass().getClassLoader(),ht.getClass().getInterfaces(),ch);
        
        duplicate.manufacture();

    }

}


Place to use -
1) When the object created is external to the system.
2) Requires access to the original object and in some cases allowing to have modified functionalities.



The code used above can be found in the link here

Facade Pattern


Definition -

    This provides a standard interface for all the interfaces in the system or sub system.   

Scenario -

    Let us take an example of building a house, the components walls, roof needs to come together in order to complete it. If you would approach to start this without the pattern then you would have to handle too many scenarios to ensure the classes are called in particular order. The facade pattern is used to make the job easier.
   
Based on the above scenario -
1) A class called walls which will build all the walls.

package FacadePattern;

public class walls {
    
    public void buildwalls() {
        System.out.println("Building walls");
    }


}

2) A class called roof which will build the roof.
package FacadePattern;

public class roofs {
    
    public void buildroofs() {
        System.out.println("Building roofs");
    }

}

3) A class called housefacade which will take care of the calling a class by the interface instead of calling roof and walls separately.
 
package FacadePattern;

public class housefacade {
    
    private walls wall=new walls();
    private roofs roof=new roofs();
    
    public void build() {
        wall.buildwalls();
        roof.buildroofs();
    }

}

4) To see the pattern in action use the code below 
package FacadePattern;

public class facadedemo {
    
    public static void main(String args[]) {
        
        housefacade house=new housefacade();
        house.build();
        
    }
    
}


Place to use -
1) Use this when you have too many interfaces and you want to simplify the interaction with the client.
2) People generally use this while building web services since a single web services will have multiple methods. 


The source for the above can be found in the link here



Decorator Pattern

Definition -

This pattern allows the designer to modify or extend the functionality of an object at run time. The speciality of this is that you can extend the capability of only one of the objects of the class.

Scenario -

    Let us take a scenario of manufacture of cars, the plant wants to modify various class for the same car depending on the order, which means some one might choose fullyloaded, basic and mid.

Based on the above this is these are the classes which we will create
1. An interface called as car. 

package DecoratorPattern;

public interface car {
    
    public void manufacture();

}

2. A basiccar class which will implement the interface car.
package DecoratorPattern;

public class basiccar implements car{

    @Override
    public void manufacture() {
        
        System.out.println("Maufacturing a basic car");
        
    }

}

3. A decorator class which implement car interface.
package DecoratorPattern;

public class decorator implements car {

    car cardemo;
    
    public decorator(car cars) {
        this.cardemo=cars;
    }
    
    @Override
    public void manufacture() {
        
        
        this.cardemo.manufacture();
        
        
    }

}

4. Two concrete decorators called fullyloaded and mid which will extend the decorator class.
fullyloaded.java
package DecoratorPattern;

public class fullyloaded extends decorator {

    public fullyloaded(car cars) {
        super(cars);
    }
    
    public void manufacture() {
        super.manufacture();
        System.out.println("Adding components of a fully loaded car");
    }

}


midlevel.java
package DecoratorPattern;

public class midlevel extends decorator {

    public midlevel(car cars) {
        super(cars);
    }
    
    public void manufacture() {
        super.manufacture();
        System.out.println("Adding components of a mid level car");
    }

}




We will first create a class called car1 and add engine and chassis as two components. Then we will clone this into car2 and display the components.

package DecoratorPattern;

public class decoratordemo {
    
    public static void main(String args[]) {
        
        car midlevelcar=new midlevel(new basiccar());
        midlevelcar.manufacture();
        
    }

}

 
Place to use -
1) When you deal with a system where if you go by normal design can create too much inheritence or sub classes.
2) You would want to add features / or modify an object in runtime.


To be careful about -
1) Since the features are added via decorators too many of these can cause maintainence issues.


The code used above can be found in the link here 



Composite Pattern

Definition -
   
    It is a pattern used when you have objects of different functionalities and you want to build structures using these, but at the same time you want all the objects to be treated in a same way.
This pattern has three components to it -
1) Base components - It is the interface for all objects in the structure.
2) Leaf - one or more base components define a leaf. This is can be called as the building blocks of the structure.
3) Composite - it contains one or more leaf nodes.

Scenario -

    Let us take an example of the construction of a Building.
1) Base components - Make
2) Leaf - Walls, roof, doors, windows
3) Composite - Floor

Based on the above this is these are the classes which we will create
1. A abstract class called Make which have an build funtion.




package CompositePattern;

public abstract class make {
    
    public abstract void build();

}

2. There are leaf objects called walls, roof.

walls.java
 package CompositePattern;

public class walls extends make{

    @Override
    public void build() {
        
        System.out.println("Building walls");
        
    }

}


roof.java
 package CompositePattern;

public class roof extends make{

    @Override
    public void build() {
       
        System.out.println("Building roof");
       
    }

}



3. Construction is a composite object
package CompositePattern;

import java.util.ArrayList;

public class construction extends make{
    
    ArrayList<make> components= new ArrayList<make>();
    

    @Override
    public void build() {
        
        for(make structures: components) {
            structures.build();
        }
        
    }
    
    
    public void addstructure(make component) {
        components.add(component);
    }


}


4. To see the pattern in action use the below code

package CompositePattern;

public class compositepatterndemo {
    
    public static void main(String args[]) {
        
        make wls=new walls();
        make rf=new roof();
        
        construction ctr=new construction();
        ctr.addstructure(wls);
        ctr.addstructure(rf);
        
        ctr.build();
        
    }

}


Place to use -
1) When objects can be made into an hierarchy and the objects can treated in a similar fashion.

Place not to use -
1) When you do not want to make your objects too generic.
2) When you cannot create hierarchy and order objects in it.

To get the code for the above use the link
here


Bridge Pattern

Bridge Pattern

Definition -
    The basis for a bridge is to decouple an abstract class from the place where it is implemented. This means the abstraction should not be binded with the implementation at compile time, rather it should be done at runtime depending on the place it is invoked.

Scenario -
Now lets take a scenario of a factory line which does both production and designing of both hatcback and sedan.
1) In this case we can consider it as two abstract entities, one is vehicle and the other is type. 


vehicle.java
 
package BridgePattern;

public abstract class vehicle {
    
    public type type1;
    public type type2;
    
    public vehicle(type type1, type type2) {
        this.type1=type1;
        this.type2=type2;
    }
    
    public abstract void manufacture();

}


type.java
 
package BridgePattern;

public interface type {
    
    public void manufacture();

}





2) hatcback and sedan are two concrete classes which will implement the vehicle interface.

hatchback.java

package BridgePattern;

public class hatchback extends vehicle {

    public hatchback(type type1, type type2) {
        super(type1, type2);
    }
    
    
    

    @Override
    public void manufacture() {
        System.out.println("Started Manufacturing a hatchback");
        type1.manufacture();
        type2.manufacture();
        
    }

}


sedan.java

package BridgePattern;

public class sedan extends vehicle {

    public sedan(type type1, type type2) {
        super(type1, type2);
    }

    @Override
    public void manufacture() {
        System.out.println("Started Manufacturing a sedan");
        type1.manufacture();
        type2.manufacture();        
    }

}





3) production and designing are two concrete classes which will implement the type interface. 

production.java

package BridgePattern;

public class production implements type {

    @Override
    public void manufacture() {
        
        System.out.println("Started production");
        
    }

}


design.java

package BridgePattern;

public class design implements type {

    @Override
    public void manufacture() {
        
        System.out.println("Started design");
        
    }
    
    

}


4) Lets see how to implement this in a client

bridgedemo.java





package BridgePattern;

public class bridgedemo {

    public static void main(String[] args) {
        
    vehicle v1=new hatchback(new design(),new production());
    v1.manufacture();
    

    }

}


Place to use -
1) When you need abstraction
2) When you do not want to bind the classes at compile time
3) When you want hierarchies to interact with each other

Place not to use -
1) Increases complexity
Did not find any other aspect to this, you are welcome with you suggestions.


The code for this can be found in github in the link here








Adapter Pattern

Definition -

This is a creational pattern. It is also reffered to as Factory of Factories. This helps designers to decouple objects from the implementing systems. Here the abstract factory will have a set of core functionalities which has to be implemented by all the factories which implement them.

Scenario -
Lets take a scenario where in you are designing a software which would display images. The image can be either jpeg / png. In future there can be other format as well where in you would want to implement in an incremental manner.  -

1) There will be an interface called imagerender where we state it can display an image. We will call this imagerender.


 
package AdapterPattern;


public interface imagerender {
    
    public void displayimage(String imagetype, String path);

}




2) Since the feature of the software is to display image of either png or jpeg we will have an image adapter which will perform the action to choose which class to implement. We will call this imageAdapter

package AdapterPattern;

public class imageAdapter implements imagerender{

    Advancedimageprocessor aip;
    
    
    public imageAdapter(String imagetype) {
        
        if(imagetype.equalsIgnoreCase("JPEG")) {
            
            System.out.println("Creating object ");
            
            aip=new jpegimage();
        }
        else if(imagetype.equalsIgnoreCase("PNG")){
            
            System.out.println("Creating object ");
            aip=new pngimage();
        }
        
    }
    
    
    @Override
    public void displayimage(String imagetype, String path) {
        
        if(imagetype.equalsIgnoreCase("JPEG")) {
            System.out.println("displaying object ");
            aip.jpegdisplay(path);
        }
        else if(imagetype.equalsIgnoreCase("PNG")) {
            System.out.println("displaying object ");
            aip.pngdisplay(path);
        }
    }
    

}



3) There will be an interface called advancedimageprocessor which will have the template for the different kinds of imageformat functionalities.

 
package AdapterPattern;

public interface Advancedimageprocessor {
    
    public void jpegdisplay(String path);
    public void pngdisplay(String path);

}


4) There will be two concrete factories called jpegimage and pngimage which will provide the actual implementation functionalities.

 jpegimage.java

 
package AdapterPattern;

public class jpegimage implements Advancedimageprocessor {
    
    public jpegimage() {
        System.out.println("Inside class jpeg image");
    }

    @Override
    public void jpegdisplay(String path) {
        
        System.out.println("Displaying jpeg image from the path: "+path);
        
    }

    @Override
    public void pngdisplay(String path) {
        // TODO Auto-generated method stub
        
    }

    

}


pngimage.java 

package AdapterPattern;

public class pngimage implements Advancedimageprocessor {
    
    
    public pngimage() {
        System.out.println("Inside class png image");
    }

    @Override
    public void jpegdisplay(String path) {
        
        
    }

    @Override
    public void pngdisplay(String path) {
        
        System.out.println("Displaying png image from the path: "+path);
        
    }
    
}



5) We will have a class called imagedisplay which call the imageAdapter.

 
package AdapterPattern;

public class imageDisplay implements imagerender{

    imageAdapter iA;
    
    public imageDisplay() {
        System.out.println("Inside imageDisplay");
    }
    
    @Override
    public void displayimage(String imagetype, String path) {
        
        System.out.println("Displaying "+ imagetype+" in path "+path);
        
        iA=new imageAdapter(imagetype);
        iA.displayimage(imagetype, path);
        
    }
    
    

}


6) Finally we will have a client called adapterClient which will be calling either PNG or JPEG formats.

package AdapterPattern;

public class adapterClient {

    public static void main(String[] args) {
        
        imageDisplay iD = new imageDisplay();
        iD.displayimage("PNG", "C:\test1");
        //iD.displayimage("JPEG", "C:\test2");

    }

}


Place to use -
1. If you require middleman between two modules and at the same time you require to ensure it is a flexible design, I cannot say it is a scalable design (You can differ on this).
2. When you want to provide temporary fix the interaction between two modules till you figure out a permanent design.
3. Although you might consider this when you want to use a plug in kind of feature, but again be careful.


Place not to use -
1. Do not use this if you have other options because debugging is quiet an headache.
2. It is not a neat design.
3. Makes maintainence of the code a nightmare.


The code for this is available in github link here

Singleton Pattern

Definition -

    The singleton pattern means you allow only one single instance of a class in the system. There are two types of singleton pattern one is early and lazy.
    The early method would instantiate the object at the first call but will ensure that new instances cannot be created.
    The lazy method would delay the creation of the instance.

Scenario -

    The singleton pattern are best used in case of database connection, where in you need to have only instance of the connection open.
   
First we will see early method

package SingletonPattern;

public class earlymethod {
    
    public static earlymethod em=new earlymethod();
    
    public static earlymethod getearlymethod() {
        return em;
    }

}


Now we will see Lazy method

package SingletonPattern;

public class Lazymethod {
    
    public static Lazymethod lm;
    
    public static Lazymethod getlm() {
        
        if(lm==null) {
            return lm=new Lazymethod();
        }
        else {
            return lm;
        }
        
    }

}


However if we use thread then we need to be more careful. The below code will show the way to handle the pattern in a multithreaded environment.

package SingletonPattern;

public class threadsafe {

    public static threadsafe ts;
    
    public synchronized static threadsafe getts() {
        if(ts==null) {
            return ts=new threadsafe();
        }else {
            return ts;
        }
    }

}



Place to use -
1) When you need a to search for an element without the need to access the representations.





Prototype Pattern

Definition -

This pattern allows you to clone an object and modify as per your wish and use it for some other operation.
When the objects that you create are complex and it is a costly operation to create one more, then we use this pattern to clone it and modify it.

Scenario -

    Let us take a scenario of building of a car. You are adding all the parts which form a car. Now creating a new object is a costly affair, hence we will clone this and then modify the parts.


Based on the above this is these are the classes which we will create
1. A car class which will keep on adding parts. We will clone the objects and modify it inside the main function.


 
package PrototypePattern;


import java.util.ArrayList;

public class car implements Cloneable {
    
    public ArrayList<parts> carparts;
    
    public car() {
        carparts = new ArrayList<parts>();
    }
    
    public car(ArrayList<parts> part) {
        this.carparts=part;
    }
    
    public void addparts(parts part) {
        carparts.add(part);
    }
    
    public ArrayList<parts> displaycomponents() {
        return carparts;
    }

    
    @Override
    public Object clone() throws CloneNotSupportedException{
        ArrayList<parts> temp=new ArrayList<parts>();
        for(parts p: carparts) {
            temp.add(p);
        }
        
        return new car(temp);
    }

}





2. A parts class which will have attribute called part name.

package PrototypePattern;

public class parts {
    
    String partname;
    
    public parts(String part) {
        this.partname=part;
    }

}





We will first create a class called car1 and add engine and chassis as two components. Then we will clone this into car2 and display the components.

package PrototypePattern;

import java.util.ArrayList;

public class prototypedemo {

    public static void main(String[] args) {
        
        ArrayList<parts> p = new ArrayList<parts>();
        parts engine = new parts("engine");
        p.add(engine);
        parts chassis = new parts("chassis");
        p.add(chassis);
        System.out.println("Creating a new object car");
        car car1=new car(p);
        ArrayList<parts> car1comp= car1.displaycomponents();
        for(parts temp: car1comp) {
            System.out.println(temp.partname);
        }
        
        try {
            car car2=(car) car1.clone();
            
            System.out.println("Cloning..");
            
            ArrayList<parts> car2comp= car2.displaycomponents();
            for(parts temp: car2comp) {
                System.out.println(temp.partname);
            }
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

    }

}





   


Place to use -
1) When you want to decouple creation and representation of an object.
2) Creating complex object.
3) Creating object which have almost similar attribute. This point is little vague, it depends on the thinking of the designer.


To be careful about -
1) This can be costly affair if this pattern is overused in the system.
2) An object having circular reference cannot use this.