Java Design pattern

 Singleton Design pattern :- 


it's Creational Design Pattern as we need to have only one instance of our class for Ex:- Logger,DBConnector.

SingleObject class have its constructor as private and have a static instance of itself.

Code:- 


       

           public class Singleton {
	private static Singleton object;

	private Singleton() {
	}

	public static synchronized Singleton getInstance() {
		if (object == null)
			object = new Singleton();
		return object;
	}
}


       
 
Eager Initialization :- 

public class Singleton {
private static Singleton object = new Singleton();

private Singleton() {
}
public static Singleton getInstance() {
return object;
}

}


Double checked Locking :- 

public class Singleton {
private static volatile Singleton obj = null;

private Singleton() {
}

public static Singleton getInstance() {
if (obj == null) {
synchronized (Singleton.class) {
if (obj == null)
obj = new Singleton();
}
}
return obj;
}
}


We have declared the obj volatile  which ensures that multiple threads offer the obj variable correctly when it is being initialized to Singleton instance. 




Factory Design pattern :- 

It is a creational design pattern which talks about the creation of an object. 

The factory method in the interface lets a class defer the instantiation to one or more concrete subclasses. 



All Source used in this blog is taken by  :- https://thecodingsimplified.com/factory-design-pattern/ 

abstract class Vehicle {
  public abstract int getWheel();
  
  public String toString() {
    return "Wheel: " this.getWheel();
  }
}

class Car extends Vehicle {
  int wheel;
  
  Car(int wheel) {
    this.wheel = wheel;
  }

  @Override
  public int getWheel() {
    return this.wheel;
  }
}

class Bike extends Vehicle {
  int wheel;
  
  Bike(int wheel) {
    this.wheel = wheel;
  }
  
  @Override
  public int getWheel() {
    return this.wheel;
  }
}

class VehicleFactory {
  public static Vehicle getInstance(String type, int wheel) {
    if(type == "car") {
      return new Car(wheel);
    else if(type == "bike") {
      return new Bike(wheel);
    }
    
    return null;
  }
}

public class FactoryPatternExample {

  public static void main(String[] args) {
    Vehicle car = VehicleFactory.getInstance("car"4);
    System.out.println(car);
    
    Vehicle bike = VehicleFactory.getInstance("bike"2);
    System.out.println(bike);
  }

}





Builder Design Pattern :- 

Builder pattern aims to “Separate the construction of a complex object from its representation so that the same construction process can create different representations.” It is used to construct a complex object step by step and the final step will return the object. 

package builder;

class Vehicle {
  //required parameter
  private String engine;
  private int wheel;
  
  //optional parameter
  private int airbags;
  
  public String getEngine() {
    return this.engine;
  }
  
  public int getWheel() {
    return this.wheel;
  }
  
  public int getAirbags() {
    return this.airbags;
  }
  
  private Vehicle(VehicleBuilder builder) {
    this.engine = builder.engine;
    this.wheel = builder.wheel;
    this.airbags = builder.airbags;
  }
  
  public static class VehicleBuilder {
    private String engine;
    private int wheel;
    
    private int airbags;
    
    public VehicleBuilder(String engine, int wheel) {
      this.engine = engine;
      this.wheel = wheel;
    }
    
    public VehicleBuilder setAirbags(int airbags) {
      this.airbags = airbags;
      return this;
    }
    
    public Vehicle build() {
      return new Vehicle(this);
    }
  }
}

public class BuilderPatternExample {
  
  public static void main(String[] args) {
    Vehicle car = new Vehicle.VehicleBuilder("1500cc"4).setAirbags(4).build();
    Vehicle bike = new Vehicle.VehicleBuilder("250cc"2).build();
    
    System.out.println(car.getEngine());
    System.out.println(car.getWheel());
    System.out.println(car.getAirbags());
    
    System.out.println(bike.getEngine());
    System.out.println(bike.getWheel());
    System.out.println(bike.getAirbags());
  }
}




ProtoType Design pattern ;- 

Prototype is a creational design pattern that allows cloning objects, even complex ones, without coupling to their specific classes.

ll prototype classes should have a common interface that makes it possible to copy objects even if their concrete classes are unknown.


package prototype;
import java.util.ArrayList;
import java.util.List;

class Vehicle implements Cloneable {
  private List<String> vehicleList;
  
  public Vehicle() {
    this.vehicleList = new ArrayList<String>();
  }
  
  public Vehicle(List<String> list) {
    this.vehicleList = list;
  }
  
  public void insertData() {
    vehicleList.add("Honda amaze");
    vehicleList.add("Audi A4");
    vehicleList.add("Hyundai Creta");
    vehicleList.add("Maruti Baleno");
    vehicleList.add("Renault Duster");
  }
  
  public List<String> getVehicleList() {
    return this.vehicleList;
  }
  
  @Override
  public Object clone() throws CloneNotSupportedException {
    List<String> tempList = new ArrayList<String>();
    
    for(String s : this.getVehicleList()) {
      tempList.add(s);
    }
    
    return new Vehicle(tempList);
  }
}

public class PrototypePatternExample {

  public static void main(String[] argsthrows CloneNotSupportedException {
    Vehicle a = new Vehicle();
    a.insertData();
    
    Vehicle b = (Vehiclea.clone();
    List<String> list = b.getVehicleList();
    list.add("Honda new Amaze");
    
    System.out.println(a.getVehicleList());
    System.out.println(list);
    
    b.getVehicleList().remove("Audi A4");
    System.out.println(list);
    System.out.println(a.getVehicleList());
  }

}



Proxy Design Pattern :- 

In proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern.

In proxy pattern, we create object having original object to interface its functionality to outer world.


package proxy;
interface DatabaseExecuter {
  public void executeDatabase(String querythrows Exception;
}

class DatabaseExecuterImpl implements DatabaseExecuter {

  @Override
  public void executeDatabase(String querythrows Exception {
    System.out.println("Going to execute Query: " + query);
  }
  
}

class DatabaseExecuterProxy implements DatabaseExecuter {
  boolean ifAdmin;
  DatabaseExecuterImpl dbExecuter;
  
  public DatabaseExecuterProxy(String name, String passwd) {
    if(name == "Admin" && passwd == "Admin@123") {
      ifAdmin = true;
    }
    dbExecuter = new DatabaseExecuterImpl();
  }

  @Override
  public void executeDatabase(String querythrows Exception {
    if(ifAdmin) {
      dbExecuter.executeDatabase(query);
    else {
      if(query.equals("DELETE")) {
        throw new Exception("DELETE not allowed for non-admin user");
      else {
        dbExecuter.executeDatabase(query);
      }
    }
  }
}

public class ProxyPatternExample {

  public static void main(String[] argsthrows Exception {
    DatabaseExecuter nonAdminExecuter = new DatabaseExecuterProxy("NonAdmin""Admin@123");
    nonAdminExecuter.executeDatabase("DELEE");
    
    DatabaseExecuter nonAdminExecuterDELETE = new DatabaseExecuterProxy("NonAdmin""Admin@123");
    nonAdminExecuterDELETE.executeDatabase("DELETE");

    
    DatabaseExecuter adminExecuter = new DatabaseExecuterProxy("Admin""Admin@123");
    adminExecuter.executeDatabase("DELETE");
    
  }

}





Bridge Design Pattern :- 

The Bridge design pattern allows you to separate the abstraction from the implementation. It is a structural design pattern. 

There are 2 parts in Bridge design pattern : 

Abstraction
Implementation



abstract class Vehicle {
    protected Workshop workShop1;
    protected Workshop workShop2;
 
    protected Vehicle(Workshop workShop1, Workshop workShop2)
    {
        this.workShop1 = workShop1;
        this.workShop2 = workShop2;
    }
 
    abstract public void manufacture();
}
 
// Refine abstraction 1 in bridge pattern
class Car extends Vehicle {
    public Car(Workshop workShop1, Workshop workShop2)
    {
        super(workShop1, workShop2);
    }
 
    @Override
    public void manufacture()
    {
        System.out.print("Car ");
        workShop1.work();
        workShop2.work();
    }
}
 
// Refine abstraction 2 in bridge pattern
class Bike extends Vehicle {
    public Bike(Workshop workShop1, Workshop workShop2)
    {
        super(workShop1, workShop2);
    }
 
    @Override
    public void manufacture()
    {
        System.out.print("Bike ");
        workShop1.work();
        workShop2.work();
    }
}
 
// Implementor for bridge pattern
interface Workshop
{
    abstract public void work();
}
 
// Concrete implementation 1 for bridge pattern
class Produce implements Workshop {
    @Override
    public void work()
    {
        System.out.print("Produced");
    }
}
 
// Concrete implementation 2 for bridge pattern
class Assemble implements Workshop {
    @Override
    public void work()
    {
        System.out.print(" And");
        System.out.println(" Assembled.");
    }
}
 
// Demonstration of bridge design pattern
class BridgePattern {
    public static void main(String[] args)
    {
        Vehicle vehicle1 = new Car(new Produce(), new Assemble());
        vehicle1.manufacture();
        Vehicle vehicle2 = new Bike(new Produce(), new Assemble());
        vehicle2.manufacture();
    }
}

Comments

Popular posts from this blog

Converting JSONArray into CSV file in java

Online Book Store Website Using Java

How to read CSV File in Java