首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

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

2013-08-04 
设计模式----原型模式(prototype pattern)AdvTemplate.java代码如下:package com.designPattern.prototype

设计模式----原型模式(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();}@Overridepublic 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<MAX_COUNT){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<maxLength;i++){sb.append(source.charAt(rand.nextInt(source.length())));}return sb.toString();}}


运行结果如下:
标题:title收件人:xuzya@sooosxsu.com发送成功标题:title收件人:areqo@krcmvkva.com发送成功标题:title收件人:wyeyy@mlocbsqt.com发送成功标题:title收件人:ezdkj@fnrmbsnp.com发送成功标题:title收件人:nmuuz@vsvhxgxi.com发送成功标题:title收件人:yrgqu@ggomwgtj.com发送成功

热点排行