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

Friday, June 25, 2021

What is annotations?

 Annotations are meta data about a class that will be processed by compiler at runtime or compile time.

Ex: when we override a method of parent class then always we see a @Override annotation that is processed at compile time . It actually inform compiler that we are overriding a method .Then compiler check the classes .

when we use annotation in spring ,the it will scan java classes for special annotation.

Automatically register bean to spring container based on annotations.

Ex:

@Component("person")

public class Person extend Human{

}

here spring will scan for component and register this class as bean to spring container .

Using the bean id "person" we can able to retrieve the bean from spring container.

Retrieve bean from spring container,

Person person = context.getBean("person",Person.class);

here context is the ApplicationContext which is spring container.

Monday, June 21, 2021

What is bean scope?

- Scope refers to the life cycle of a bean .

-How long does the bean will alive

-How the bean will share

-How many instances will created

By default bean scope is singleton.

Singleton: Spring container will create single instance .All request for the bean will return a shared reference for that bean.


Other scopes:

-Prototype:Create new reference and return it .
 


Sunday, June 20, 2021

What is dependency injection?

Ans: Dependency means something that is dependent on something .When an object dependent on another object then that object is the dependent object. Ex: if we assume car is an object then tire ,door, machine is the dependent object of car. So, dependency injection means of injecting dependent object from object factory(Spring container) throw constructor/setter/autowiring .

Dependency can be injected throw -

1.Constructor injection

2.Setter injection

3.Autowiring.

Wednesday, June 16, 2021

Function of Spring container-->>

 --Create and manage object(IOC-Inversion of control)

--Inject object dependencies(Dependency injection)








--Spring container generically known as ApplicationContext

Ex:xml based





Javascript module

JavaScript Modules (ES6) let you split code into multiple files and reuse code cleanly. Main keywords: export → make something available...