原型模式(Prototype)
程序员文章站
2022-06-12 21:46:36
...
在Java语言里深复制一个对象,常常可以先使对象实现Serializable接口,然后把对象(实际上只是对象的一个拷贝)写到一个内存数组流里(腌成咸菜),再从流里读回来(把咸菜回鲜),便可以重建对象。
package prototype;
import java.io.IOException;
import java.io.OptionalDataException;
public interface Prototype extends Cloneable{
/**
* 浅复制
* @return
*/
public Object clone() ;
/**
* 深复制
* @return
* @throws IOException
* @throws OptionalDataException
* @throws ClassNotFoundException
*/
public Object deepClone() throws IOException, OptionalDataException,
ClassNotFoundException;
}
/**
*
*/
package prototype;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
/**
* @author Administrator
*
*/
public class ConcretePrototype implements Prototype {
/**
* 浅复制
*/
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
/**
* 深复制
* @return
* @throws IOException
* @throws OptionalDataException
* @throws ClassNotFoundException
*/
public Object deepClone() throws IOException, OptionalDataException,
ClassNotFoundException
{
// write to stream
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
// read from stream
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return (oi.readObject());
}
}
d