package com.DesignPattern.Creational.Prototype;
public interface Prototype extends Cloneable {
//克隆方法
Prototype clone();
}
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;
}
}
}
package com.DesignPattern.Creational.Prototype;
public class Client {
public void operation(Prototype example) {
// 得到example的副本
Prototype p = example.clone();
}
}
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;
}
}
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();
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载|Copyright ©2011-2015,Supernatural, All Rights Reserved.
DesignPattern_Java:Prototype Pattern
原文地址:http://blog.csdn.net/williamfan21c/article/details/47985153