Advertisement
atanasovetr

PrototypeExample_GFG

May 25th, 2021
826
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1.  
  2. // A Java program to demonstrate working of
  3. // Prototype Design Pattern with example
  4. // of a ColorStore class to store existing objects.
  5.  
  6. import java.util.HashMap;
  7. import java.util.Map;
  8.  
  9.  
  10. abstract class Color implements Cloneable
  11. {
  12.      
  13.     protected String colorName;
  14.        
  15.     abstract void addColor();
  16.        
  17.     public Object clone()
  18.     {
  19.         Object clone = null;
  20.         try
  21.         {
  22.             clone = super.clone();
  23.         }
  24.         catch (CloneNotSupportedException e)
  25.         {
  26.             e.printStackTrace();
  27.         }
  28.         return clone;
  29.     }
  30. }
  31.  
  32. class blueColor extends Color
  33. {
  34.     public blueColor()
  35.     {
  36.         this.colorName = "blue";
  37.     }
  38.    
  39.     @Override
  40.     void addColor()
  41.     {
  42.         System.out.println("Blue color added");
  43.     }
  44.      
  45. }
  46.  
  47. class blackColor extends Color{
  48.    
  49.     public blackColor()
  50.     {
  51.         this.colorName = "black";
  52.     }
  53.    
  54.     @Override
  55.     void addColor()
  56.     {
  57.         System.out.println("Black color added");
  58.     }
  59. }
  60.    
  61. class ColorStore {
  62.    
  63.     private static Map<String, Color> colorMap = new HashMap<String, Color>();
  64.        
  65.     static
  66.     {
  67.         colorMap.put("blue", new blueColor());
  68.         colorMap.put("black", new blackColor());
  69.     }
  70.        
  71.     public static Color getColor(String colorName)
  72.     {
  73.         return (Color) colorMap.get(colorName).clone();
  74.     }
  75. }
  76.  
  77.  
  78. // Driver class
  79. class Prototype
  80. {
  81.     public static void main (String[] args)
  82.     {
  83.         ColorStore.getColor("blue").addColor();
  84.         ColorStore.getColor("black").addColor();
  85.         ColorStore.getColor("black").addColor();
  86.         ColorStore.getColor("blue").addColor();
  87.     }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement