1. 含义
通过给出一个原型对象来指明所要创建的对象的类型,然后用复制这个原型对象的方法创建出更多同类型的对象.
2.类图
简单形式
登记形式
3.类代码
简单形式
/**
* 抽象原型角色
*
*/
public interface Prototype extends Cloneable {
Object clone();
}
/**
* 具体原型角色
*/
public class ConcretePrototype implements Prototype{
public Object clone() {
try{
return (Prototype)super.clone();
}catch(CloneNotSupportedException e){
return null;
}
}
}
/**
* 客户角色
*/
public class Client {
private Prototype prototype;
public void operation(Prototype example) {
prototype = (Prototype) example.clone();
S.s(example);
S.s(prototype);
}
public static void main(String[] a) {
Client c = new Client();
c.operation(new ConcretePrototype());
}
}
登记形式
/**
* 抽象原型角色
*
*/
public interface Prototype extends Cloneable {
Object clone();
}
/**
* 具体原型角色
*/
public class ConcretePrototype implements Prototype {
@SuppressWarnings("finally")
public synchronized Object clone() {
Prototype temp = null;
try {
temp = (Prototype) super.clone();
return temp;
} catch (CloneNotSupportedException e) {
S.s("Clone failed.");
} finally {
return temp;
}
}
}
/**
* 原型管理器角色
*/
public class PrototypeManager {
private Vector objects = new Vector();
public void add(Prototype p) {
objects.add(p);
}
public Prototype get(int i) {
return (Prototype) objects.get(i);
}
public int getSize() {
return objects.size();
}
}
/**
* 客户角色
*/
public class Client {
public PrototypeManager pm = new PrototypeManager();
private Prototype prototype;
public void registerPrototype() {
prototype = new ConcretePrototype();
Prototype copytype = (Prototype) prototype.clone();
pm.add(copytype);
}
public static void main(String[] a) {
Client c = new Client();
c.registerPrototype();
c.registerPrototype();
S.s(c.pm.getSize());
}
}
4. 深复制
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* 具体原型角色
*/
public class ConcretePrototype implements Prototype, Serializable {
public Object clone() {
Prototype concretePrototype = null;
try {
concretePrototype = (Prototype)deepClone();
return concretePrototype;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
return concretePrototype;
}
}
/**
* 通过在流里读来读去的方式来实现深复制
*
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
public Object deepClone() throws IOException, ClassNotFoundException {
// 将对象写到流里
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
// 从流里读回来
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return oi.readObject();
}
}
z