Merge 073707cbe805f72ef5944c7d5bd64524c1dd3cfa into b70121d377cb6005eb65f12b098cd5decd905669
This commit is contained in:
commit
1c4ef7bed4
@ -54,3 +54,42 @@ abc
|
|||||||
### JDK
|
### JDK
|
||||||
|
|
||||||
- [java.lang.Object#clone()](http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone%28%29)
|
- [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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user