设计模式----原型模式(prototype pattern)

AdvTemplate.java代码如下:

package com.designPattern.prototype;

public class AdvTemplate {

private String advSubject = "title";

private String advContext = "context";

public String getAdvSubject() {
return advSubject;
}

public String getAdvContext() {
return advContext;
}

}



Mail.java代码如下:

package com.designPattern.prototype;

/**
*
* @author yangjianzhou
* 使用原型模式时需要注意的几个问题:
* 1.对象拷贝时,类的构造函数是不会被执行的
* 2.浅拷贝与深拷贝的问题
* 3.clone与final的关系
*/
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.getAdvContext();
this.subject = advTemplate.getAdvSubject();
}

@Override
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 getContext() {
return context;
}

public void setContext(String context) {
this.context = context;
}

public String getTail() {
return tail;
}

public void setTail(String tail) {
this.tail = tail;
}

}



Client.java代码如下:

package com.designPattern.prototype;

import java.util.Random;

public class Client {

private static int MAX_COUNT = 6;

public static void main(String[] args) {
int i=0;
Mail mail = new Mail(new AdvTemplate());
mail.setTail("XX银行版权所有");
while(i Mail cloneMail = mail.clone();
cloneMail.setAppellation(getRandString(5)+"先生(女士)");
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发送成功");
}

public static String getRandString(int maxLength){
String source = "abcdefghijklmnopqrstuvwxyz";

StringBuffer sb = new StringBuffer();
Random rand = new Random();
for(int i=0;i sb.append(source.charAt(rand.nextInt(source.length())));
}

return sb.toString();
}

}



运行结果如下:

标题:title 收件人:[email protected] 发送成功
标题:title 收件人:[email protected] 发送成功
标题:title 收件人:[email protected] 发送成功
标题:title 收件人:[email protected] 发送成功
标题:title 收件人:[email protected] 发送成功
标题:title 收件人:[email protected] 发送成功

你可能感兴趣的:(design,patterns)