ProtoType Pattern 原型模式的简单程度是仅次于单例模式的:
实现原型模式只需要满足:
1. 原型类实现Cloneable接口;
2. 原型类中实现覆盖Object类的clone()方法;
例如我们的业务需求是:给每个客户发送一封定制广告邮件,
那么首先需要一个广告模板,然后从数据库中取出客户的定制信息,使用模板生成一份完整的邮件,发送出去。
import java.util.Random;
//业务对象BO类,或者DTO(Data Transfer Object)类
class Mail {
private String receiver;
private String context;
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
}
public class Client {
//客户数量
private static int NUMBER = 6;
public static void main(String[] args){
Mail mail = new Mail();
int i = 0;
while(i < NUMBER){
mail.setReceiver("MR."+getRandomString(4)+"@"+getRandomString(5)+" Company");
mail.setContext(getRandomString(20)+"\n");
send(mail);
i++;
}
}
private static void send(Mail mail){
System.out.println(mail.getReceiver());
System.out.println(mail.getContext());
}
private static String getRandomString(int length){
StringBuffer sb = new StringBuffer();
Random rand = new Random();
for(int i = 0;i < length;i++){
char j = (char) ('a'+rand.nextInt(26));
sb.append(j);
}
return sb.toString();
}
}
考虑下这个程序是否有问题?
1. 一封邮件发送0.01秒,很短吧,如果需要发送给100万个客户呢?—效率低
2. 用多线程吧!会有线程安全问题吧!如果加锁,速度依然很慢。。—不安全,效率也不高
3. 因此,通常情况下,对于这种每个对象非常相似,又需要很多个的情况,就可以考虑使用原型模式了。那么如何修改呢?
其实很简单:
- 将OB类实现Cloneable接口;
- 然后在其中重写Object的clone()方法;
- 最后在客户端用一个原型实例拷贝就行了。
import java.util.Random;
class Mail implements Cloneable{
private String receiver;
private String context;
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
@Override
protected Mail clone() {
Mail mail = null;
try {
//调用Java提供的拷贝方法---Object类的(浅拷贝)
mail = (Mail)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return mail;
}
}
public class Client {
//客户数量
private static int NUMBER = 6;
public static void main(String[] args){
Mail mail = new Mail();
int i = 0;
while(i < NUMBER){
//浅拷贝
Mail cloneMail = mail.clone();
cloneMail.setReceiver("MR."+getRandomString(4)+"@"+getRandomString(5)+" Company");
cloneMail.setContext(getRandomString(20)+"\n");
send(cloneMail);
i++;
}
}
private static void send(Mail mail){
System.out.println(mail.getReceiver());
System.out.println(mail.getContext());
}
private static String getRandomString(int length){
StringBuffer sb = new StringBuffer();
Random rand = new Random();
for(int i = 0;i < length;i++){
char j = (char) ('a'+rand.nextInt(26));
sb.append(j);
}
return sb.toString();
}
}