package com.DesignPattern.Creational.Prototype;
public class ConcretePrototype implements Prototype {
@Override
public Prototype clone() {
try {
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
}
客户角色(Client):该角色提出创建对象的请求。
package com.DesignPattern.Creational.Prototype;
public class Client {
public void operation(Prototype example) {
// 得到example的副本
Prototype p = example.clone();
}
}
原型模式的实例
Mail.java
package com.DesignPattern.Creational.Prototype;
public class Mail implements Cloneable {
private String receiver;
private String subject;
private String appellation;
private String contxt;
private String tail;
public Mail(String subject, String contxt) {
this.subject = subject;
this.contxt = contxt;
}
// 克隆方法
public Mail clone() {
Mail mail = null;
try {
mail = (Mail) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return mail;
}
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 getContxt() {
return contxt;
}
public void setContxt(String contxt) {
this.contxt = contxt;
}
public String getTail() {
return tail;
}
public void setTail(String tail) {
this.tail = tail;
}
}
ClientDemo.java
package com.DesignPattern.Creational.Prototype;
import java.util.Random;
public class ClientDemo {
// 发送账单的数量,这个值是从数据库中获得的
private static int MAX_COUNT = 6;
public static void main(String[] args) {
int i = 0;
// 定义一个邮件对象
Mail mail = new Mail("Activity", "there are ...");
mail.setAppellation("copyright");
while (i < MAX_COUNT) {
// 克隆邮件
Mail cloneMail = mail.clone();
cloneMail.setAppellation(getRandString(5) + "G(M)");
cloneMail.setReceiver(getRandString(5) + "@" + getRandString(8)
+ ".com");
// 发送邮件
sendMail(cloneMail);
i++;
}
}
// 发送邮件
public static void sendMail(Mail mail) {
System.out.println("标题:" + mail.getSubject() + "\t收件人:"
+ mail.getReceiver() + "\t.....send Success!");
}
// 获得指定长度的随机字符串
public static String getRandString(int maxLength) {
String source = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuffer sb = new StringBuffer();
Random rand = new Random();
for (int i = 0; i < maxLength; i++) {
sb.append(source.charAt(rand.nextInt(source.length())));
}
return sb.toString();
}
}
原型模式 Prototype PatternSpecify the kinds of objects to create using a prototypical instance,and create new objects by copying this prototype.用原型实例指定创建对象的种类,并且通过复制这些原型创建新的对象。Java内置克隆机制:实现Cloneable接口覆盖Obj