设计模式之原型模式
原型设计模式主要使用场景:
1、类初始化需要消耗非常多的资源
2、通过new 产生一个对象需要非常繁琐的数据准备或者访问权限,
下面就使用发送广告邮件为例说明原型设计模式的使用。
当发送广告邮件时,邮件中除了称呼和接受地址会变之外,其他都是一样的,所以我们可以将不变的地方抽取出来作为一个模版(AdvTemplate),然后定义一个邮件类,编写一个构造方法,参数就是上面的模板,根据模板来创建 邮件。代码如下:
public class AdvTemplate{//广告信名称private String advSubject="中国农业银行国庆信用卡抽奖活动";//广告信内容private String advContext="你好,你已经被系统抽中,请立刻到附近的中国农业银行领取100万现金....";//获得广告信标题public String getAdvSubject(){return advSubject;}//获得广告信内容public String getAdvContext(){return advContext;}}
编写一个邮件类:
public class Mail implements Cloneable{private String receiver;private String subject;private String appellation;private String context;private String tail;//构造函数public Mail(AdvTemplate tem){this.subject=tem.getAdvSubject();this.context=tem.getAdvContext();}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;}@Overridepublic Mail clone() {// TODO Auto-generated method stubMail mail=null;try{mail=(Mail)super.clone();} catch (CloneNotSupportedException e){// TODO Auto-generated catch blocke.printStackTrace();}return mail;}}
编写一个客户类:
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("中国农业银行版权所有");while(i<MAX_COUNT){Mail temp=mail.clone();temp.setAppellation(getRandomString(4)+" 先生(女士)");temp.setReceiver(getRandomString(4)+"@"+getRandomString(5)+".com");sendMail(temp);i++;}}public static String getRandomString(int len){String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";StringBuffer buf=new StringBuffer();Random random=new Random();for(int i=0;i<len;i++){buf.append(str.charAt(random.nextInt(str.length())));}return buf.toString();}public static void sendMail(Mail mail){System.out.println("标题:"+mail.getSubject()+"\t"+"收件人:"+mail.getReceiver()+"\t 发送成功...");}}