Last active
May 22, 2019 12:23
-
-
Save bayraktugrul/f78aa88f1baddfb923a568722004647a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Hashtable; | |
public abstract class Shape implements Cloneable { | |
private String id; | |
protected String type; | |
abstract void draw(); | |
public String getType(){ | |
return type; | |
} | |
public String getId() { | |
return id; | |
} | |
public void setId(String id) { | |
this.id = id; | |
} | |
public Object clone() { | |
Object clone = null; | |
try { | |
clone = super.clone(); | |
} catch (CloneNotSupportedException e) { | |
e.printStackTrace(); | |
} | |
return clone; | |
} | |
} | |
public class Rectangle extends Shape { | |
public Rectangle(){ | |
type = "Rectangle"; | |
} | |
@Override | |
public void draw() { | |
System.out.println("Inside Rectangle::draw() method."); | |
} | |
} | |
public class Square extends Shape { | |
public Square(){ | |
type = "Square"; | |
} | |
@Override | |
public void draw() { | |
System.out.println("Inside Square::draw() method."); | |
} | |
} | |
public class Circle extends Shape { | |
public Circle(){ | |
type = "Circle"; | |
} | |
@Override | |
public void draw() { | |
System.out.println("Inside Circle::draw() method."); | |
} | |
} | |
public class ShapeCache { | |
private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>(); | |
public static Shape getShape(String shapeId) { | |
Shape cachedShape = shapeMap.get(shapeId); | |
return (Shape) cachedShape.clone(); | |
} | |
// Her Shape için veritabanı sorgusu çalıştığını varsay ve objeleri oluştur | |
// shapeMap.put(shapeKey, shape); | |
// Örneğin, 3 adet shape objesi oluşturduk | |
public static void loadCache() { | |
Circle circle = new Circle(); | |
circle.setId("1"); | |
shapeMap.put(circle.getId(),circle); | |
Square square = new Square(); | |
square.setId("2"); | |
shapeMap.put(square.getId(),square); | |
Rectangle rectangle = new Rectangle(); | |
rectangle.setId("3"); | |
shapeMap.put(rectangle.getId(), rectangle); | |
} | |
} | |
public class PrototypePatternDemo { | |
public static void main(String[] args) { | |
ShapeCache.loadCache(); | |
Shape clonedShape = (Shape) ShapeCache.getShape("1"); | |
System.out.println("Shape : " + clonedShape.getType()); | |
Shape clonedShape2 = (Shape) ShapeCache.getShape("2"); | |
System.out.println("Shape : " + clonedShape2.getType()); | |
Shape clonedShape3 = (Shape) ShapeCache.getShape("3"); | |
System.out.println("Shape : " + clonedShape3.getType()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment