设计模式-原型模式
原型类
public abstract class Shape implements Cloneable{
private String id;
protected String type;
abstract void draw();
@Override
protected Object clone() {
Object clone = null;
try{
clone = super.clone();
}catch (CloneNotSupportedException e){
e.printStackTrace();
}
return clone;
}
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;
}
}
对应的扩展实体类A,B,C
public class A extends Shape {
public A(){
type = "a";
}
@Override
void draw() {
System.out.println("draw a");
}
}
public class B extends Shape{
public B() {
type = "b";
}
@Override
void draw() {
System.out.println("draw b");
}
}
public class C extends Shape {
public C() {
type = "c";
}
@Override
void draw() {
System.out.println("draw c");
}
}
测试一下
public class Test {
private static Map<String,Shape> shapeMap = new HashMap<>();
public static Shape getShape(String shapeId){
Shape temp = shapeMap.get(shapeId);
return (Shape)temp.clone();
}
public static void loadCache() {
A circle = new A();
circle.setId("1");
shapeMap.put(circle.getId(),circle);
B square = new B();
square.setId("2");
shapeMap.put(square.getId(),square);
C rectangle = new C();
rectangle.setId("3");
shapeMap.put(rectangle.getId(),rectangle);
}
public static void main(String[] args) {
Test.loadCache();
Shape clonedShape = (Shape) Test.getShape("1");
System.out.println("Shape : " + clonedShape.getType());
Shape clonedShape2 = (Shape) Test.getShape("2");
System.out.println("Shape : " + clonedShape2.getType());
Shape clonedShape3 = (Shape) Test.getShape("3");
System.out.println("Shape : " + clonedShape3.getType());
}
}
输出