定义
用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
克隆生成对象
结构
Prototype:声明一个克隆自身的接口,用来约束想要克隆自己的类,要求它们都要实现这里定义的克隆方法。
ConcretePrototype:实现Prototype接口的类,这些类真实实现了克隆自身的功能。
Client:使用原型的客户端,首先要获取到原型实例对象,然后通过原型实例克隆自身来创建新的对象实例。
代码
public class Client {
private Prototype prototype;
public Client(Prototype prototype) {
this.prototype = prototype;
}
public void operation(){
Prototype prototype = this.prototype.clone();
}
}
interface Prototype{
Prototype clone();
}
class ConcretePrototype1 implements Prototype{
@Override
public Prototype clone() {
ConcretePrototype1 prototype1 = new ConcretePrototype1();
return prototype1;
}
}
class ConcretePrototype2 implements Prototype{
@Override
public Prototype clone() {
ConcretePrototype2 prototype2 = new ConcretePrototype2();
return prototype2;
}
}
new操作活得的实例的属性一般是没有值或者是默认值,如果通过克隆得到的实例的属性是有值的,属性值就是原型对象在克隆的时候的属性值。
JAVA中的原型模式
java中Object类已经定义了clone()方法,需要克隆功能的类只需要实现java.lang.Cloneable接口就好。
class ConcretePrototype implements Cloneable{
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
浅度克隆深度克隆
浅度克隆:只负责克隆按值传递的数据(比如基本数据类型,String类型)。
深度克隆:除了浅度克隆要克隆的值外,还负责克隆引用类型的数据,基本上就是被克隆实例所有的属性数据都会被克隆出来。
通过给引用类型属性添加克隆方法来实现深度克隆
class Product implements Cloneable{
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Order implements Cloneable{
private Product product;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Order order = (Order)super.clone();
order.setProduct((Product)product.clone());
return order;
}
}
通过序列化的方式来实现深度克隆(推荐)
class Product implements Serializable {
}
class Order implements Serializable {
private Product product;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
@Override
protected Object clone() throws CloneNotSupportedException {
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
Order order = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(this);
bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
order = (Order) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ois.close();
bis.close();
oos.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return order;
}
}
原型管理器
管理原型资源的资源管理器。
class PrototypeManager{
private static Map<String,Prototype> map = new HashMap<>();
private PrototypeManager(){}
public synchronized static void setPrototype(String prototypeId,Prototype prototype){
map.put(prototypeId,prototype);
}
public synchronized static void removePrototype(String prototypeId){
map.remove(prototypeId);
}
private synchronized static Prototype getPrototype(String prototypeId){
return map.get(prototypeId);
}
}