Saturday, June 4, 2022

Design Pattern: Prototype Pattern

Chapters

Prototype Pattern

Prototype pattern is a creational design pattern that copies(clone) an object rather than re-creating it. In Object Oriented Programming (OOP), objects are created by instantiating a class.

In java, there's a clone() method that we can use to clone an object rather than re-creating it via instantiation. In this pattern, we create an interface (or abstract class). Then, the client can use the interface to clone its concrete implementations. Take a look at this example.
import java.util.List;
import java.util.Random;

public class ClientCode{
  
  public static void main(String[] args)
                throws CloneNotSupportedException{
    Prototype protoA = 
    new ConcretePrototypeA("protoA");
    
    System.out.println("Original");
    protoA.displayList();
    System.out.println("\n");
    
    Prototype cloneObj = protoA.clone();
    System.out.println("Clone");
    cloneObj.displayList();
    System.out.println("\n");
    
    System.out.println("Compare Instance");
    System.out.println(
    protoA.compareListInstance(cloneObj.getList()));
  }
}

//factory class
interface Prototype extends Cloneable{
  
  Prototype clone() throws CloneNotSupportedException;
  void displayList();
  boolean compareListInstance(List<Integer> list);
  List<Integer> getList();
}

class ConcretePrototypeA implements Prototype{
  private List<Integer> numbers;
  
  ConcretePrototypeA(String name){
    Random rand = new Random();
    Integer[] values = new Integer[5];
    for(int i = 0; i < values.length; i++)
      values[i] = rand.nextInt(1000);
    numbers = java.util.Arrays.asList(values);
  }
  
  @Override
  public Prototype clone() throws CloneNotSupportedException{
    return (ConcretePrototypeA) super.clone();
  }
  
  public void displayList(){
    numbers.stream().forEach(v -> System.out.print(v + " "));
  }
  
  public boolean compareListInstance(List<Integer> list){
    return list == numbers;
  }
  
  public List<Integer> getList(){
    return numbers;
  }
  
}

Result(may vary)
Original
588 68 607 122 106

Clone
588 68 607 122 106

Compare Instance
true
You can use this pattern when you want to create another Object at runtime that is a true copy of the Object you are cloning. True copy means all the attributes of the newly created Object should be the same as the Object you are cloning.

No comments:

Post a Comment