Showing posts with label Creation Pattern. Show all posts
Showing posts with label Creation Pattern. Show all posts

Monday, December 11, 2017

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.

Factory Pattern

Definition -
   
    When you can abstract the functionalities and use that object to call other classes which implement the

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. A abstract class called carmanufacture which have an execute funtion to process the request of the client. 



package SimpleFactoryPattern;

public class hatchback extends carmanufacture{

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

}




2. There are two sub classes called hatchback and sedan which will extend the abstract class.

hatchback.java

package SimpleFactoryPattern;

public class hatchback extends carmanufacture{

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

}







sedan.java    



package SimpleFactoryPattern;

public class sedan extends carmanufacture {

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

}


3. To see the pattern in action use the following code - 

package SimpleFactoryPattern;

public class factorydemo {
    
    public static void main(String args[]) {
        
        carmanufacture car=null;
        
        String order = "Hatchback";
        
        if(order.equalsIgnoreCase("Hatchback")) {
            car = new hatchback();
            
        }
        
        else if(order.equalsIgnoreCase("Sedan")) {
            car=new sedan();
        }
        
        car.manufacture();
        
    }

}


Place to use -
1) When you want the client to decide on the sub class at run time.
2) When you can abstract a class and there is not too much deviation in the way the different sub classes work.

Place not to use -
1) Can easily over complicate design.
2) When there are too many changes and each change introduces few attributes / functionalities not used by others then it might result in change.




Builder Pattern

Definition -
    As the name suggests this pattern builds an object in a step by step manner. The pattern will follow a series of steps defined hence the designer should define a sequence. This pattern allows more granular control over the system. In this pattern there will be a director, a builder and a client. The client issues a request,
    The director will order the builder to build an object according to the request and submits to the client. This pattern helps to simplify construction of a complex object into small easier steps.
   

Scenario -

    Lets take an example of assembly line where in you want the software to take care of constructing different vehicles like hatchback or sedan.
Based on this if we have to use this pattern to design the software then -
1. We need to have a interface which will provide the standard steps for constructing the vehicles. Let us call this interface as vehiclebuilder.



package BuilderPattern;

public interface vehiclebuilder {
    
    public void buildengine();
    public void buildchassis();
    public void assemble();

}



2. We need to have concerete classes which will implement the builder class. Let us call these classes as hatchback builder and sedanbuilder.


hatchback.java



package BuilderPattern;

public class hatchbackbuilder implements vehiclebuilder {

    @Override
    public void buildengine() {
        
        System.out.println("Building engine for a hatchback");
        
    }

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

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

}



sedanbuilder.java


package BuilderPattern;

public class sedanbuilder implements vehiclebuilder {

    @Override
    public void buildengine() {
        
        System.out.println("Building engine for a sedan");
        
    }

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

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

}



3. We will have a director who is responsible for invoking the classes based on the order it recieves from the client.


package BuilderPattern;

public class builddirector {
    
    public void createvehicle(vehiclebuilder vb) {
        vb.buildengine();
        vb.buildchassis();
        vb.assemble();
    }

}




The client code will look -



package BuilderPattern;

public class builderpatterndemo {
    
    public static void main(String args[]) {
        
        builddirector bd=new builddirector();
        vehiclebuilder builder=null;
        builder=new hatchbackbuilder();
        bd.createvehicle(builder);
        
    }

}



Place to use -
1. To be used when creation has to be decoupled from the system.
2. When you need to add flexbility to add new functionality without affecting the system.
3. When you need more granular control over the runtime creation of objects.



Place not to use -
1. Too much flexbility and decoupling may add to complexity. This might result in maintainence overhead.

Saturday, December 9, 2017

Abstract Factory Pattern

Definition -

This is a creation pattern. It is also referred 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 you are required to work with different protocols and you have to execute certain functions based irrespective of the protocol but the method of implementation is different.
In this case lets assume we have to deal with TCP and UDP protocols and each one of them have to read the data on a port. The reading of the data is different for TCP and UDP.

The UML diagram is as shown below



Based on the above -

protocolImplementor is an abstract class.
the concrete factories will be tcpprotocol and udpprotocol which will implement the read and processing functionality.

So here we have an abstract factory which defines two functionalities.

The two concrete factories tcpprotocol and udpprotocol will implement the abstract factory.

In the main method, we are invoking the classes depending on the requirement. There are other methods to invoke this which include creating an instance of the abstract factory and then invoking the class which is required. I have just maintained this for simplicity.

Code

We will have an abstract Interface called:  protocolImplementor

package FactoryPattern;

public abstract interface protocolImplementor {
    
    public void readport(int port);
    public void processdata();

}

The below two classes tcpprotocol and udpprotocol will implement the interface as shown below - 

package FactoryPattern;

public class tcpprotocol implements protocolImplementor {
    
    public tcpprotocol() {
        System.out.println("Initializing tcp protocol");
    }

    @Override
    public void readport(int port) {
        
        System.out.println("tcp method: Reading port:"+port);
        
    }

    @Override
    public void processdata() {
        
        System.out.println("tcp method: processing data");
        
    }

}


package FactoryPattern;

public class udpprotocol implements protocolImplementor{
    
    
    public udpprotocol() {
        System.out.println("Initializing udp protocol");
    }

    @Override
    public void readport(int port) {
        
        System.out.println("udp method: Reading port:"+port);
        
    }

    @Override
    public void processdata() {
        
        System.out.println("udp method: processing data");
        
    }

}



Then we will have a client abstractfactoryclient which will show us demo of the pattern

package FactoryPattern;

public class abstractfactoryclient {

    public static void main(String[] args) {
        
        String protocol="TCP";;
        int port=8080;
        
        if(protocol=="TCP") {
            tcpprotocol tcp=new tcpprotocol();
            tcp.readport(port);
            tcp.processdata();
        }
        
        if(protocol=="UDP") {
            udpprotocol udp=new udpprotocol();
            udp.readport(port);
            udp.processdata();
        }

    }

}


Place to use -
1. If you have multiple platforms and you require to use one of them depending on the scenario.
2. You want to provide a library without exposing the implementation details.
3. You want to ensure your implementation is platforms independent.
4. If you have products which needs to adhere to a minimum set of functionalities and the client program can choose this at runtime.


Place not to use -
1. Do not use this if you have too many objects being passed.
2. If the future extension requires new functionalities, which would mean we would implement the interface but we would not use it. This would result in a very bad design.
3. If there are too many attributes being introduced in the future.