原型模式也是23种设计模式里比较简单的模式之一,一句话概括原型模式,复制粘贴。类似windows上的复制粘贴,可以帮你克隆出一个新的对象,但是又和之前的不等(地址不一样,没有引用同一个对象)
public class Yuanxing implements Cloneable { public Yuanxing() { System.out.println("创建对象成功"); } public Yuanxing clone() throws CloneNotSupportedException{ return (Yuanxing)super.clone(); } }
public class Client { public static void main(String[] args) throws CloneNotSupportedException { Yuanxing yuanxing = new Yuanxing(); Yuanxing yuanxing1 = yuanxing.clone(); System.out.println(yuanxing==yuanxing1);//false } }
需要克隆的类要实现Cloneable接口且抛出异常,在方法内调用所有对象的超类Object类中的clone()方法。
应用场景:某个对象创建很麻烦的时候,或者某几个对象大致属性都相同,但个别属性不同的时候,这时候重新创建对象是很麻烦的,不如直接clone然后修改单个不同的属性