设计模式之原型模式

原型模式(创建对象种类,并且通过复制这些原型来创建新的对象)
原型模式实现
Cloneable接口和clone方法。
Prototype模式中实现起来最困难的地方就是内存复制操作,所幸在Java中提供了clone()方法替我们做了绝大部分事情。
原型模式的三种角色
客户角色:
提出创建对象的请求
抽象原型角色:
由java接口或抽象类实现,给出所有的具体原型类需要的接口
具体原型角色:
被复制的对象,实现抽象原型接口
实例如下

1.抽象原型角色接口:Cloneable
2.具体原型角色:Email

public class Email implements Cloneable{
private String receive;   //接收人
private String title;        //标题
private String context;  //内容

//构造方法
public Email(String title,String context){
this.title = title;
this.context = context;
}

public Email clone(){
Email email = null;
try{
email = (Email) super.clone();
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return email;
}

//get,set方法
public String getReceive(){
return receive;
}

public void setReceive(String receive){
this.receive = receive;
}

public String getTitle(){
return title;
}

public void setTitle(String title){
this.title= title;
}

public String getContext(){
return context;
}

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

3.客户角色:

public class BMWClient{
List<String> receiveList =new ArrayList<String>();

public List<String> getEmailList(){
receiveList.add("赵");
receiveList.add("钱");
receiveList.add("孙");
receiveList.add("李");
return receiveList;

public void sendEmail(Email email) {
        System.out.println("发送邮件給:" + email.getReceive() + ",标题:" + email.getTitle() + ",内容:" + email.getContext());
    }
}

4.原型模式调用者

public class keyDemo(){
public static void main(String[] args){
Email email = new Email("hello,欢迎来到BMW");
BMWClient client = new BMWClient();//客户对象
int num = client.getEmailList().size();//客户个数
for(int i = 0;i<num;i++){
Email cEmail = email.clone();//复制的新对象
String receive = client.getEmailList().get(i);//获取收件人
cEmail .setReceive(receive);
client.sendEmail(cEmail );//发送邮件
}
}
}

猜你喜欢

转载自blog.csdn.net/qq_28198893/article/details/79173137