意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
一、原型模式
原型模式应用场景主要在于当一个对象的创建非常复杂,消耗很多资源之时。如果一个对象的创建之前需要经过很过步骤和要求,一般情况对象用完就会销毁。但为了避免资源的消耗。可以把对象存住,下次使用时直接复制原型。
java 克隆
二、代码
原料
主要在于实现java对象的克隆
package prototype;
public abstract class Shape implements Cloneable {
private String id;
protected String type;
abstract void draw();
public void setId(String id){
this.id = id;
}
public String getId() {
return id;
}
public Object clone() {
Shape clone = null;
try {
clone = (Shape)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
package prototype;
public class Rectangle extends Shape{
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("Rectangle");
}
}
package prototype;
public class Square extends Shape {
public Square(){
type = "Square";
}
@Override
public void draw() {
System.out.println("Square");
}
}
容器
package prototype;
import java.util.Hashtable;
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();
}
public static void loadCache() {
Square square = new Square();
square.setId("1");
shapeMap.put(square.getId(),square);
Rectangle rectangle = new Rectangle();
rectangle.setId("2");
shapeMap.put(rectangle.getId(),rectangle);
}
public static void main(String[] args) {
ShapeCache.loadCache();
Shape clonedShape1 = (Shape) ShapeCache.getShape("1");
System.out.println(clonedShape1.type);
Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
System.out.println(clonedShape2.type);
}
}