原型模式实例
原型模式主要用于对一个对象的克隆以及深拷贝,使对象所有属性进行复制的同时并不会造成相同地址的引用。
首先可以实现Cloneable接口使对象可以实现克隆。再通过重写父类的clone方法来实现对象的克隆,如出现对象嵌套操作的话则需要实现深拷贝。
public class PrototypeTest {
public static void main(String[] args) throws CloneNotSupportedException {
BaseInfo baseInfo = new BaseInfo("XXX");
Product product = new Product("part1", "part2", "part3",baseInfo);
Product clone = product.clone();
System.out.println(product);
System.out.println(clone);
product.getBaseInfo().setCompanyName("YYY");
System.out.println(product);
System.out.println(clone);
}
}
class BaseInfo implements Cloneable,Serializable{
private String companyName;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public BaseInfo(String companyName) {
this.companyName = companyName;
}
@Override
protected BaseInfo clone() throws CloneNotSupportedException {
return (BaseInfo) super.clone();
}
@Override
public String toString() {
return super.hashCode()+"|BaseInfo{" +
"companyName='" + companyName + '\'' +
'}';
}
}
class Product implements Cloneable,Serializable{
private String part1;
private String part2;
private String part3;
private BaseInfo baseInfo;
public Product() {
}
public Product(String part1, String part2, String part3,BaseInfo baseInfo) {
this.part1 = part1;
this.part2 = part2;
this.part3 = part3;
this.baseInfo = baseInfo;
}
public BaseInfo getBaseInfo() {
return baseInfo;
}
public void setBaseInfo(BaseInfo baseInfo) {
this.baseInfo = baseInfo;
}
public String getPart1() {
return part1;
}
public void setPart1(String part1) {
this.part1 = part1;
}
public String getPart2() {
return part2;
}
public void setPart2(String part2) {
this.part2 = part2;
}
public String getPart3() {
return part3;
}
public void setPart3(String part3) {
this.part3 = part3;
}
@Override
protected Product clone(){
Product clone = (Product) super.clone();
BaseInfo clone1 = this.baseInfo.clone();
clone.setBaseInfo(clone1);
return clone;
}
@Override
public String toString() {
return super.hashCode()+"|Product{" +
"part1='" + part1 + '\'' +
", part2='" + part2 + '\'' +
", part3='" + part3 + '\'' +
", baseInfo=" + baseInfo +
'}';
}
}
也可以使用流的操作来实现对象的拷贝。
@Override
protected Product clone(){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(byteArrayOutputStream);
oos.writeObject(this);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
try {
ObjectInputStream ois = new ObjectInputStream(byteArrayInputStream);
Product object = ((Product) ois.readObject());
return object;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
应用场景
当代码不应该依赖于需要复制的对象的具体类时,需要使用原型模式。
优点
- 可以在不耦合具体类的情况下克隆对象。
- 避免重复的初始化代码。
- 更方便的构建复杂的数据结构。