diff --git "a/notes/\350\256\276\350\256\241\346\250\241\345\274\217 - \345\216\237\345\236\213\346\250\241\345\274\217.md" "b/notes/\350\256\276\350\256\241\346\250\241\345\274\217 - \345\216\237\345\236\213\346\250\241\345\274\217.md" index 50dc005a95..b2197fae70 100644 --- "a/notes/\350\256\276\350\256\241\346\250\241\345\274\217 - \345\216\237\345\236\213\346\250\241\345\274\217.md" +++ "b/notes/\350\256\276\350\256\241\346\250\241\345\274\217 - \345\216\237\345\236\213\346\250\241\345\274\217.md" @@ -54,3 +54,42 @@ abc ### JDK - [java.lang.Object#clone()](http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone%28%29) + +### 4、原型模式 + +①使用原型模式的初衷是用对象来创建对象,而不是用new 类()的方式来创建对象。 + +②优点是加载类的过程比较耗费时间,而使用对象拷贝为新对象的方式可以提高性能 + +实现方式: + +原型类实现Cloneable接口,重写clone()方法 + +```java +public class Prototype implements Cloneable{ + + @Override + public Prototype clone() throws CloneNotSupportedException { + Prototype clone = (Prototype) super.clone(); + return clone; + } +} +``` + +客户端使用原型模式: + +```java +public class Client { + + public static void main(String[] args) throws CloneNotSupportedException { + Prototype prototype = new Prototype(); + + for (int i = 0; i < 100; i++) { + Prototype clone = prototype.clone(); + System.out.println("克隆出的新对象:" + clone); + } + } +} +``` + +