原型模式定義:用原型實例指定建立對象的種類,而且經過拷貝這些原型建立新的對象。java
首先了解原型模式以前咱們先理解一下Cloneable這個類:安全
原型模式使用場景:app
/** * @author Lin * @Date 2018/1/5. */ public class Mail implements Cloneable{ /** * 收件人 */ private String receiver; /** * 郵件名稱 */ private String subject; /** * 稱謂 */ private String appellation; /** * 郵件內容 */ private String content; /** * 郵件尾部信息 */ private String tail; public Mail(AdvTemplate advTemplate){ this.content = advTemplate.getAdvContent(); this.subject = advTemplate.getAdvSubject(); } @Override protected 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 getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTail() { return tail; } public void setTail(String tail) { this.tail = tail; } }
/** * @author Lin * @Date 2018/1/5. */ public class AdvTemplate { /** * 廣告信名稱 */ private String advSubject = "xx銀行過年信用卡抽獎活動"; /** * 廣告信內容 */ private String advContent = "國慶抽獎活動通知:只要你刷卡就送你一個億。。。。"; public String getAdvSubject() { return advSubject; } public String getAdvContent() { return advContent; } }
import java.util.Random; /** * @author Lin * @Date 2018/1/5. */ 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 mailClone = mail.clone(); mailClone.setAppellation(getRandString(5) + "先生(女士)"); mailClone.setReceiver(getRandString(5) + "@" + getRandString(8) + ".com"); sendMail(mailClone); i++; } } public static void sendMail(Mail mail){ System.out.println("標題:" + mail.getSubject() + "\t收件人:" + mail.getReceiver() + "\t.....發送成功!"); } public static String getRandString(int maxLength){ String source = "abcdefghijklnmopqrstuvwxyzABCDEFGHIJKLNMOPQRSTUVWXYZ"; 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(); } }