设计模式-原型模式

一、所需要的类

一个实现克隆接口的类

二、实现代码

实现克隆接口的类代码

java 复制代码
class SimplePrototype implements Cloneable {
    private String name;
    private int value;
    
    public SimplePrototype(String name, int value) {
        this.name = name;
        this.value = value;
    }
    
    @Override
    public SimplePrototype clone() {
        try {
            return (SimplePrototype) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new AssertionError(); // 不会发生
        }
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public void setValue(int value) {
        this.value = value;
    }
    
    @Override
    public String toString() {
        return "SimplePrototype{name='" + name + "', value=" + value + "}";
    }
}

调用类

java 复制代码
public class SimplePrototypeDemo {
    public static void main(String[] args) {
        SimplePrototype original = new SimplePrototype("Original", 100);
        SimplePrototype copy = original.clone();
        
        System.out.println("Original: " + original);
        System.out.println("Copy: " + copy);
        
        copy.setName("Copy");
        copy.setValue(200);
        
        System.out.println("\nAfter modification:");
        System.out.println("Original: " + original);
        System.out.println("Copy: " + copy);
    }
}

三、结论

原型模式的作用就是降低在创建 对象时的成本,因为创建一个对象可能会传很多参数。