原型模式就是通过原型创建多个对象,简单来说就是通过一个对象去复制多个对象
类图如下
原型模式类图
需要实现Cloneable接口,复写clone()方法
具体代码如下
public class Mail implements Cloneable{
private String receiver;
private String subject;
private String appellation;
private String context;
private String tail;
public Mail(AdvTemplate advTemplate){
this.context = advTemplate.advContext();
this.subject = advTemplate.getAdvSubject();
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getAppellation() {
return appellation;
}
public void setAppellation(String appellation) {
this.appellation = appellation;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public String getTail() {
return tail;
}
public void setTail(String tail) {
this.tail = tail;
}
@Override
protected Mail clone(){
Mail mail = null;
try {
mail = (Mail)super.clone();
}catch (CloneNotSupportedException e){
}
return mail;
}
}
我们在调用是可 mail.clone();用于复制对象,直接重堆中复制对象,不会调用类的构造函数
这里需要注意浅拷贝和深拷贝
浅拷贝:我们在进程clone时只会拷贝基本数据类型不会拷贝引用数据类型和内部数组,如果需要拷贝要对私有对象进行独立拷贝(深拷贝)
@Override
protected Mail clone(){
Mail mail = null;
try {
mail = (Mail)super.clone();
this.list = (ArrayList<String>)this.list.clone();
}catch (CloneNotSupportedException e){
}
return mail;
}
如果需要拷贝那不能使用final来修饰
网友评论