一、UML

Prototype.png
二、基本步驟
2.1、創(chuàng)建需要使用原型模式的類,實(shí)現(xiàn)Cloneable接口;
2.2、重寫clone()方法,使用其父類的clone()方法構(gòu)建一個(gè)對(duì)象;
2.3、將原對(duì)象的各個(gè)成員依次拷貝(賦值)給新創(chuàng)建的對(duì)象;
2.4、將新對(duì)象返回,需要做異常處理;
三、實(shí)現(xiàn)方式
3.1、定義
/**
* @author lizihanglove
* @date 2018/1/12
* @email one_mighty@163.com
* @desc 原型設(shè)計(jì)模式
*/
public class UrlPrototype implements Cloneable {
private String host;
private String port;
private String protocol;
public void printUrl() {
System.out.println("The Url is:"+protocol+"http://"+host+":"+port);
}
@Override
public UrlPrototype clone() {
try {
UrlPrototype urlPrototype = (UrlPrototype) super.clone();
urlPrototype.host = this.host;
urlPrototype.port = this.port;
urlPrototype.protocol = this.protocol;
return urlPrototype;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
}
3.2、調(diào)用
UrlPrototype original = new UrlPrototype();
original.setHost("www.lizihanglove.website");
original.setPort("8080");
original.setProtocol("https");
original.printUrl();
System.out.println("--------------------------------------");
UrlPrototype reborn = original.clone();
reborn.printUrl();
System.out.println("--------------------------------------");
reborn.setPort("80");
reborn.setProtocol("http");
reborn.printUrl();
3.3、結(jié)果
System.out: The Url is:https//www.lizihanglove.website:8080
System.out: --------------------------------------
System.out: The Url is:https//www.lizihanglove.website:8080
System.out: --------------------------------------
System.out: The Url is:http//www.lizihanglove.website:80