Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

原型模式更改建议 #1164

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions notes/设计模式 - 原型模式.md
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
```