Showing posts with label Design patterns. Show all posts
Showing posts with label Design patterns. Show all posts

Wednesday, March 12, 2025

Abstract factory pattern

When single task can be done by multiple groups/family of objects and decision is taken at the runtime.




 

Sunday, February 13, 2022

Prototype design pattern

 Prototype design pattern is a creational design pattern. It is used when object creation is costly and we want to use same object . So we can create prototype of the current object and can use it . let's see the example,

Book class-

public class Book {

private int bid;

private String bname;

public Book(int bid, String bname) {

super();

this.bid = bid;

this.bname = bname;

}


public int getBid() {

return bid;

}

public void setBid(int bid) {

this.bid = bid;

}

public String getBname() {

return bname;

}

public void setBname(String bname) {

this.bname = bname;

}

@Override

public String toString() {

return "Book [bid=" + bid + ", bname=" + bname + "]";

}

//BookShop class--

public class BookShop implements Cloneable {// must implement cloneable interface to copy of the                                                                                      object

private String shopName;

private List<Book> books;

public BookShop(String shopName) {

super();

this.shopName = shopName;

books = new ArrayList<Book>();

}

public String getShopName() {

return shopName;

}

public void setShopName(String shopName) {

this.shopName = shopName;

}

public List<Book> getBooks() {

return books;

}

public void setBooks(List<Book> books) {

this.books = books;

}

public void loadBooks() {

for (int i = 0; i < 10; i++) {

Book book = new Book(i, "book" + i);

books.add(book);

}

}

@Override

protected Object clone() throws CloneNotSupportedException { //should override clone() method

return super.clone();

}

@Override

public String toString() {

return "BookShop [shopName=" + shopName + ", books=" + books + "]";

}

}

//Main class

public class MainApp {

public static void main(String[] args) {

BookShop shop1 = new BookShop("shop 1");

shop1.loadBooks();

System.out.println(shop1);

try {

BookShop shop2 =(BookShop) shop1.clone();

shop2.setShopName("shop2");

System.out.println(shop2);

} catch (CloneNotSupportedException e) {

e.printStackTrace();

}

}

}



Saturday, February 12, 2022

Factory design pattern

Task can be done by multiple objects(a group of objects) and specific object can be decided at runtime  ;

Let's see an example.

//parent class

public interface Phone{

void makeCall();

}

//subclass 1

public class AndroidPhone implements Phone {

@Override

public void makeCall() {

System.out.println("calling using android phone");

}

}

//subclass 2

public class Iphone implements Phone {

@Override

public void makeCall() {

System.out.println("Calling using iphone.");

}

}

//subclass 3

public class Windows implements Phone {

@Override

public void makeCall() {

System.out.println("calling using windows phone.");

}

}

//factory

public PhoneFactory{

public Phone getPhone(String phoneName){

if(phoneName.equals("Android")){

return new AndroidPhone();

}

else if(phoneName.equals("lphone")){

return new Lphone();

}

else{

return new Windows();

}

}

//MainClass

public static void main(String[] args){

PhoneFactory phoneFactory = new PhoneFactory();

Phone phone = phoneFactory.getPhone("Android");

phone.makeCall();

}


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

Testing controller

------Controller------------- @RestController @RequestMapping("/items") public class ItemController {     private final ItemServic...