课程大纲 / Lesson 05
Prototype 创建型

Prototype · 原型

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

01

理解原型模式:通过克隆已有对象来创建新对象,避免重复初始化的开销

02

掌握浅克隆与深克隆的区别,以及 Cloneable 接口的使用方式

03

理解原型缓存(ShapeCache)的使用场景:需要重复创建相似对象时

04

了解原型模式与工厂模式的对比,以及各自适用场景

核心概念
克隆复制对象浅克隆与深克隆原型缓存Cloneable 接口
classDiagram class shape { <<interface>> +clone() shape +draw() } class circle { -x int -y int -r int +clone() shape +draw() } class rectangle { -x int -y int -width int -height int +clone() shape +draw() } class shapecache { -cache hashmap~string,shape~$ +loadcache()$ +getshape(id string) shape$ } shape <|.. circle shape <|.. rectangle shapecache o-- shape

原型通过 clone 复制已有对象,避免客户端与具体类的构造过程耦合

点击 Run 克隆图形...
/** 原型接口:所有图形实现此接口以支持克隆 */
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 更高效。

◈

浅克隆 vs. 深克隆

默认 Object.clone() 为浅克隆(引用类型字段复制地址);若含可变引用字段,需实现深克隆。

◈

原型缓存场景

ShapeCache 预先存储原型,运行时通过 getShape(key).clone() 获取副本,适合需要大量相似对象的场景(如游戏子弹、UI 图形)。

◈

原型 vs. 工厂模式

工厂模式通过子类决定创建什么,原型模式通过克隆已有对象创建;原型适合对象种类在运行时才能确定的场景。