简单例子
我需要创建一个人,这个人除了Id不同,其他都一样。
package mode.prototype;
/**
* @author gang.tu
*/
public class Body {
Body(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
}
package mode.prototype;
/**
* @author gang.tu
*/
public class Head {
Head(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
}
package mode.prototype;
/**
* @author gang.tu
*/
public class Person implements Cloneable {
private String id;
private Body body;
private Head head;
@Override
public Person clone() {
Person person = null;
try {
person = (Person) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return person;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Body getBody() {
return body;
}
public void setBody(Body body) {
this.body = body;
}
public Head getHead() {
return head;
}
public void setHead(Head head) {
this.head = head;
}
}
单元测试
在package mode.prototype;
import org.junit.Test;
import static org.junit.Assert.*;
public class PersonTest {
@Test
public void test() {
Body body = new Body("body");
Head head = new Head("head");
Person person = new Person();
person.setBody(body);
person.setHead(head);
person.setId("1");
System.out.println(person.getId());
System.out.println(person.getBody().getName());
System.out.println(person.getHead().getName());
Person person1 = person.clone();
person1.setId("2");
System.out.println(person1.getId());
System.out.println(person1.getBody().getName());
System.out.println(person1.getHead().getName());
}
}
运行结果:
1
body
head
2
body
head
总结
- 原型模式主要关键词:实现Cloneable接口,实现clone方法。
- 实现clone方法为浅拷贝。
- 当构建一个对象非常复杂时或者创建成本非常高时可以使用。
- clone不会运行构造方法。

被折叠的 条评论
为什么被折叠?



