[TOC]
介绍
Specify the kinds of objects to create using a prototypical instance,and create new objects by copying this prototype.(用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。) -- 设计模式之禅第二版
是创建型模式的一种
实现
基本思想:克隆内容,返回新对象.这个新对象可以进行定制
用代码实现的话,只需要一个可以进行拷贝的JavaBean就可以了
代码类似这样:
public class Prototype implements Cloneable, Serializable {
private int a;
public Prototype(){
}
public Prototype(int a){
this.a = a;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return(Prototype)super.clone();
}
}
使用
例如使用一个发一个广告邮件,广告信息是公共的,更改收件人信息
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class MailPrototype implements Cloneable, Serializable {
private String receiver;
private String content;
@Override
protected Object clone() throws CloneNotSupportedException {
return (MailPrototype) super.clone();
}
}
class Run {
public static void main(String[] args) {
MailPrototype prototype = new MailPrototype("receiver1", "大法1000xm4新品发售啦!!!");
MailPrototype prototype1 = null;
MailPrototype prototype2 = null;
try {
prototype1 = (MailPrototype) prototype.clone();
prototype1.setReceiver("receiver2");
prototype2 = (MailPrototype) prototype.clone();
prototype2.setReceiver("receiver3");
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
System.out.println(prototype);
System.out.println(prototype1);
System.out.println(prototype2);
}
}
因为使用拷贝,所以相比使用构造创建来讲,更快些,但是这也引入拷贝的问题,应注意浅拷贝与深拷贝的问题