原型模式 深拷贝和浅拷贝
- 当代码不依赖于需要复制的对象的具体类时,可使用原型模式
- 可以不耦合具体类的情况下克隆对象
- 避免重复的初始化操作
- 更方便的构建复杂对象
实现:
public class PrototypeTest {
public static void main(String[] args) {
Product product = new Product(1, 2, new BaseInfo("aaa", "bbb"));
Product clone = product.clone();
System.out.println(product);
System.out.println(clone);
product.getBaseInfo().setAddress("ccc");
System.out.println(product);
System.out.println(clone);
}
}
@Getter
@Setter
class Product implements Cloneable,Serializable {
private Integer part1;
private Integer part2;
private BaseInfo baseInfo;
public Product() {
}
public Product(Integer part1, Integer part2, BaseInfo baseInfo) {
this.part1 = part1;
this.part2 = part2;
this.baseInfo = baseInfo;
}
@Override
public String toString() {
return "Product[" + this.hashCode() + ",part1=" + this.part1 + ",part2=" + this.part2 + ","+this.baseInfo + "]";
}
@Override
public Product clone() {
//使用clone方式
// try {
// Product clone = (Product) super.clone();
// clone.setBaseInfo(this.baseInfo.clone());
// return clone;
// } catch (Exception e) {
// throw new AssertionError();
// }
// 使用流的方式 不建议使用 属于CPU密集型
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(byteArrayOutputStream)){
oos.writeObject(this);
} catch (Exception e) {
e.printStackTrace();
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
try (ObjectInputStream ois = new ObjectInputStream(byteArrayInputStream)){
Product product = (Product) ois.readObject();
return product;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
@Setter
@Getter
class BaseInfo implements Cloneable,Serializable {
private String address;
private String content;
public BaseInfo() {
}
public BaseInfo(String address, String content) {
this.address = address;
this.content = content;
}
@Override
public String toString() {
return "BaseInfo(address=" + this.address + ",content=" + this.content + ")";
}
@Override
public BaseInfo clone() {
try {
return (BaseInfo) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}