Thursday, July 15, 2021

Singleton design pattern?

 Singleton is an creational design pattern where a single instance is exist of a class at runtime .

Advantage:

If there raise such a situation where we want to restrict not to create more than one object ,just provide a mechanism to use that object then singleton is suitable process.

Ex:Database connection class could be singleton 

How to write a singleton class?

steps 1. declare a static type instance to store the instance.

step 2.make the default constructor private .

step3.declare a static public method to return that static object.

below is the example,

Singleton: (Single threaded)

final public class Singleton {
    private static Singleton INSTANCE = null;
    private String value;

    private Singleton(String value) {
        this.value = value;
    }
    public String getValue() {
        return value;
    }
    public static Singleton getInstance(String value) {
        if (null == INSTANCE)
            INSTANCE = new Singleton(value);
        return INSTANCE;
    }
}

MainApp:

    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance("xyz");
        System.out.println(singleton.getValue());
       
        Singleton singleton2 = Singleton.getInstance("abc");
        System.out.println(singleton.getValue());
    }

The given example is working fine in with single threaded application . But what if it is in multithreaded application . lets see the example,

    public static void main(String[] args) {
        Thread foo = new Thread(() -> {
            Singleton singleton1 = Singleton.getInstance("foo");
            System.out.println(singleton1.getValue());
        });

        Thread bar = new Thread(() -> {
            Singleton singleton2 = Singleton.getInstance("bar");
            System.out.println(singleton2.getValue());
        });
        foo.start();
        bar.start();
    } 

output:

foo
bar

It is showing wrong output because each thread is writing value to their own cache of OS. One thread doesn't know about the value of others. 

So how to resolve it ? 

Ans: Make the instance creational method synchronized

let see the example - 

public static Singleton getInstance(String value) {
        Singleton result = INSTANCE;
        if (null != result)
            return result;
        synchronized (Singleton.class) {
            if (INSTANCE == null) {
                INSTANCE = new Singleton(value);
            }
            return INSTANCE;
        }
    }

We can introduce the synchronized block using Lock of that class. So that only one thread who first acquire that block can create the object . Others thread can not acquire the block . Whenever object is created others thread will always get that already created object . Because we assigned created object into the result variable.


 



 


Tuesday, July 6, 2021

Builder design pattern ?

 This is a type of creational design pattern where user can create object without specifying all the parameter of the constructor to build the object using a builder .

Advantage:

1.No need to specify all the parameter into constructor .

2.No need to maintain parameter sequence in constructor .

3.User can create object by their need .

Ex:

PC class:

public class PC {

private String ram;

private String processor;

private String hdd;

private String motherBoard;


public PC(String ram, String processor, String hdd, String motherBoard) {

super();

this.ram = ram;

this.processor = processor;

this.hdd = hdd;

this.motherBoard = motherBoard;

}

@Override

public String toString() {

return "PC [ram=" + ram + ", processor=" + processor + ", hdd=" + hdd + ", motherBoard=" + motherBoard + "]";

}

}

Builder class:

package builderDesignPatternImplementation;

public class PcBuilder {
private String ram;
private String processor;
private String hdd;
private String motherBoard;

public PcBuilder setRam(String ram) {
this.ram = ram;
return this;
}

public PcBuilder setProcessor(String processor) {
this.processor = processor;
return this;
}

public PcBuilder setHdd(String hdd) {
this.hdd = hdd;
return this;
}

public PcBuilder setMotherBoard(String motherBoard) {
this.motherBoard = motherBoard;
return this;
}

public PC getPC() {
return new PC(ram, processor, hdd, motherBoard);
}
}

Main App:

public class MainApp {

public static void main(String[] args) {

PcBuilder builder = new PcBuilder();
PC pc = builder.setProcessor("core i7").setHdd("samsung").getPC();
System.out.println(pc.toString());
}

}

Thursday, July 1, 2021

Types of design pattern?

There are 3 types of design pattern mainly.
1.Creational design pattern.
2.Structural  design pattern .
3.Behavioral design pattern .

1.Creational design pattern: Mainly focus on object creation mechanism ,which provides flexibility and reuse of existing code.

Types of creational design pattern-
       1.Singleton
       2.Factory
       3.Builder
       4.Abstract factory
       5.Prototype

2.Structural design pattern: Structural design pattern explain how to assemble objects and classes into larger structure while keeping these structure flexible and efficient .

Types of structural design pattern:
      1.Adapter
      2.Composite 
      3.Proxy
      4.Fly weight
      5.Facade 
      6.Decorator
      7.Bridge

3.Behavioral design pattern: This design pattern is concerned with algorithm and the assignment of responsibilities among object not to compose each other .
ex:
 1.observer
2.Memento
3.Strategy
4.Iterator
5.Chain
6.Command
7.State
8.Visitor

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...