用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
理解原型模式:通过克隆已有对象来创建新对象,避免重复初始化的开销
掌握浅克隆与深克隆的区别,以及 Cloneable 接口的使用方式
理解原型缓存(ShapeCache)的使用场景:需要重复创建相似对象时
了解原型模式与工厂模式的对比,以及各自适用场景
原型通过 clone 复制已有对象,避免客户端与具体类的构造过程耦合
/** 原型接口:所有图形实现此接口以支持克隆 */
public interface Shape extends Cloneable {
Shape clone();
void draw();
}/** 圆形原型 */
public class Circle implements Shape {
private int x, y, r;
public Circle(int x, int y, int r) {
this.x = x; this.y = y; this.r = r;
}
public Shape clone() {
return new Circle(x, y, r);
}
public void draw() {
System.out.println("Drawing Circle at (" + x + "," + y + ") r=" + r);
}
}/** 矩形原型 */
public class Rectangle implements Shape {
private int x, y, width, height;
public Rectangle(int x, int y, int w, int h) {
this.x = x; this.y = y; width = w; height = h;
}
public Shape clone() {
return new Rectangle(x, y, width, height);
}
public void draw() {
System.out.println("Drawing Rectangle at (" + x + "," + y
+ ") " + width + "x" + height);
}
}import java.util.HashMap;
/** 原型缓存:存储预先生成的图形原型,供客户端克隆使用 */
public class ShapeCache {
private static HashMap<String, Shape> cache =
new HashMap<>();
public static void loadCache() {
Circle c = new Circle(1, 1, 10);
Rectangle r = new Rectangle(0, 0, 20, 20);
cache.put("circle", c);
cache.put("rectangle", r);
}
public static Shape getShape(String key) {
return cache.get(key).clone();
}
}public class Demo {
public static void main(String[] args) {
ShapeCache.loadCache();
Shape c1 = ShapeCache.getShape("circle");
Shape c2 = ShapeCache.getShape("circle");
c1.draw();
c2.draw();
System.out.println("c1 == c2: " + (c1 == c2));
}
}当创建对象成本较高(如数据库查询、复杂计算)时,通过 clone() 复制已有原型比 new 更高效。
默认 Object.clone() 为浅克隆(引用类型字段复制地址);若含可变引用字段,需实现深克隆。
ShapeCache 预先存储原型,运行时通过 getShape(key).clone() 获取副本,适合需要大量相似对象的场景(如游戏子弹、UI 图形)。
工厂模式通过子类决定创建什么,原型模式通过克隆已有对象创建;原型适合对象种类在运行时才能确定的场景。