创建型-原型模式
程序员文章站
2022-06-13 15:53:47
...
目录
不使用设计模式
可能是这样的
public class WithoutPrototypePatternDemo {
public static void main(String[] args) {
// 手头有这么一个对象,需要进行拷贝
Product product = new Product("测试产品", new Component("测试组件"));
// 手动来拷贝
Product copyProduct = new Product(product.getName(), product.getComponent());
System.out.println(copyProduct);
}
public static class Component {
private String name;
public Component(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Component [name=" + name + "]";
}
}
public static class Product {
private String name;
private Component component;
public Product(String name, Component component) {
super();
this.name = name;
this.component = component;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Component getComponent() {
return component;
}
public void setComponent(Component component) {
this.component = component;
}
@Override
public String toString() {
return "Product [name=" + name + ", component=" + component + "]";
}
}
}
存在的问题
代码的拷贝逻辑,是每个要拷贝的调用方自己来实现的
相同的拷贝逻辑会分散在很多不同的地方,如果拷贝逻辑改变了,多个调用的地方都要修改代码
可维护性、可扩展性,很差
使用了原型模式
public class PrototypePatternDemo {
public static void main(String[] args) {
try {
Product product = new Product("测试产品", new Component("测试组件"));
Product copyProduct = (Product) product.clone();
System.out.println(copyProduct);
} catch (Exception e) {
e.printStackTrace();
}
// 原型模式,就是在要拷贝的类里实现一个clone()方法,自己拷贝自己
// 拷贝的时候,就两个概念,浅拷贝,深拷贝
// 很多地方要克隆这个对象,不要自己维护克隆的逻辑,即使克隆逻辑修改了,只要在clone()方法里面修改
}
public static class Component {
private String name;
public Component(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Component [name=" + name + "]";
}
@Override
protected Object clone() throws CloneNotSupportedException {
return new Component(getName());
}
}
public static class Product {
private String name;
private Component component;
public Product(String name, Component component) {
super();
this.name = name;
this.component = component;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Component getComponent() {
return component;
}
public void setComponent(Component component) {
this.component = component;
}
@Override
public String toString() {
return "Product [name=" + name + ", component=" + component + "]";
}
@Override
protected Object clone() throws CloneNotSupportedException {
// 浅拷贝,就是我们现在的一个实现
// 就是仅仅简单的对当前所有的变量进行一个拷贝
// return new Product(getName(), getComponent());
// 深考别,递归对自己引用的对象也进行拷贝
return new Product(getName(), (Component)getComponent().clone());
}
}
}