5) Prototype Pattern

发布时间 2023-06-06 13:27:42作者: zno2

类别:

 Creational Pattern

问题:

 不想修改原对象状态,但需要依据当前数据进行计算

方案:

 

 

 

示例:

 

public class PrototypePattern {
    public static void main(String[] args) {
        Movie movie = new Movie();
        movie.setName("xxxxxx");
        Movie clone = movie.clone();
        System.out.println(clone.getName());
        System.out.println(clone == movie);
    }
}

class Movie implements Cloneable {
    public String name = null;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public Movie clone() {
        System.out.println("Cloning Movie object..");
        try {
            return (Movie) super.clone();
        } catch (CloneNotSupportedException e) {
            // never happen , the class has implements Cloneable
            throw new RuntimeException();
        }
    }

    @Override
    public String toString() {
        return "Movie";
    }
}

 

应用:

分析:

1. 需实现 java.lang.Cloneable 接口 (如果不继承Cloneable 会报 CloneNotSupportedException)

2. 子类的clone方法需要调用super的clone() 不然调用自己的会递归栈溢出

Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.

 

不足:(

 

优化:)