design pattern prototype

Prototype pattern (create kind of objects and create new objects by copying these prototypes)
prototype pattern implementation :
Cloneable interface and clone method.
The most difficult part to implement in Prototype mode is the memory copy operation. Fortunately, the clone() method is provided in Java to do most of the things for us.
Three roles of prototype pattern
Client role:
request to create an object
Abstract prototype role:
implemented by java interface or abstract class, giving all the interfaces required by concrete prototype class
Concrete prototype role:
copied object, implement abstract prototype interface
Instance as follows :

1. Abstract prototype role interface: Cloneable
2. Concrete prototype role: 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. Customer role:

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. Prototype pattern caller

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 );//发送邮件
}
}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325849668&siteId=291194637