原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。
思考: 通过克隆的方式来创建重复的对象
package day0316.PrototypePattern;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.UUID;
public class PrototypePatternDemo{
public static void main(String[] args) throws CloneNotSupportedException{
System.out.println("============= EMULATE READING DATA FROM DATABASE ===============");
ShapeCache.loadCache();
Shape clonedShape = (Shape) ShapeCache.getShape("1");
System.out.println("Shape : " + clonedShape.getType());
}
}
class ShapeCache {
static Map<String, Shape> shapeMap = new Hashtable<String, Shape>();
static Shape getShape(String shapeId) throws CloneNotSupportedException{
Shape cachedShape = shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}
public static void loadCache() {
Circle circle = new Circle("Circle " + UUID.randomUUID(), "Circle");
System.out.println(circle);
shapeMap.put(circle.getId(),circle);
Square square = new Square("Square " + UUID.randomUUID(), "Square");
System.out.println(square);
shapeMap.put(square.getId(),square);
Rectangle rectangle = new Rectangle("Rectangle " + UUID.randomUUID(), "Rectangle");
System.out.println(rectangle);
shapeMap.put(rectangle.getId(),rectangle);
}
}
abstract class Shape implements Cloneable{
String id;
String type;
public Shape(String id, String type){
this.id = id;
this.type = type;
}
public String getId(){
return id;
}
public void setId(String id){
this.id = id;
}
public String getType(){
return type;
}
public void setType(String type){
this.type = type;
}
@Override
public Object clone() throws CloneNotSupportedException{
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
@Override
public String toString(){
String template = "[%s] ID: %s, TYPE: %s";
return String.format(template, this.getClass().getName(), this.getId(), this.getType());
}
}
class Circle extends Shape {
public Circle(String id, String type){
super(id, type);
}
}
class Rectangle extends Shape {
public Rectangle(String id, String type){
super(id, type);
}
}
class Square extends Shape {
public Square(String id, String type){
super(id, type);
}
}
原文:https://www.cnblogs.com/litran/p/10641173.html