原型模式
UML
![原型模式](https://i-blog.csdnimg.cn/blog_migrate/0ff300b5b46410dcb0763d3d1a55c9b5.png)
解释说明
- 原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
- 浅拷贝:若是引用类型的字段,复制其引用。
- 深拷贝:若是引用类型的字段,创建新的对象再引用。
- java中创建浅表副本可以通过实现 Cloneable 接口。
代码实现
package learn06;
public class InfoEntity implements Cloneable {
private String name;
private int age;
public InfoEntity(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
package learn06;
public abstract class Prototype {
private int id;
private InfoEntity info;
public Prototype(int id, String name, int age) {
this.id = id;
this.info = new InfoEntity(name, age);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setInfo(InfoEntity info) {
this.info = info;
}
public InfoEntity getInfo() {
return info;
}
@Override
public abstract Prototype clone();
}
package learn06;
public class ConcretePrototype extends Prototype {
public ConcretePrototype(int id, String name, int age) {
super(id, name, age);
}
private ConcretePrototype(InfoEntity info) {
super(0, "", 0);
InfoEntity infoEntity = null;
try {
infoEntity = (InfoEntity) info.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
this.setInfo(infoEntity);
}
public void display() {
System.out.println("id:" + getId() + " name:" + getInfo().getName() + " age:" + getInfo().getAge());
}
@Override
public Prototype clone() {
ConcretePrototype concretePrototype = new ConcretePrototype(this.getInfo());
concretePrototype.setId(this.getId());
return concretePrototype;
}
}
import learn06.*;
public class Main {
public static void main(String[] args) {
ConcretePrototype a = new ConcretePrototype(1, "Jack", 20);
ConcretePrototype b = (ConcretePrototype) a.clone();
b.setId(2);
b.getInfo().setName("Tim");
b.getInfo().setAge(21);
a.display();
b.display();
}
}
参考资料