原型模式(Prototype):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
下面是原型模式的结构图:
下面就演示一个Demo:
首先创建一个抽象类Prototype,它要实现Cloneable接口,重写clone方法,只有这样类才具有克隆的功能
abstract class Prototype implements Cloneable{
private String name;
private String event;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getEvent() {
return this.event;
}
public void setEvent(String event) {
this.event = event;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
然后创建两个子类:
public class ConcretePrototype1 extends Prototype{
public ConcretePrototype1(String name, String event) {
this.setName(name);
this.setEvent(event);
}
public void print() {
System.out.println("ConcretePrototype1 Name:" + this.getName() + " Event:" + this.getEvent());
}
}
public class ConcretePrototype2 extends Prototype{
public ConcretePrototype2(String name, String event) {
this.setName(name);
this.setEvent(event);
}
public void print() {
System.out.println("ConcretePrototype2 Name:" + this.getName() + " Event:" + this.getEvent());
}
}
接着就是客户端:
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
/**
* 正常创建对象
*/
ConcretePrototype1 cp1 = new ConcretePrototype1("Xxx", "play");
ConcretePrototype2 cp2 = new ConcretePrototype2("Zzz", "do");
cp1.print();
cp2.print();
/**
* Copy两个对象
*/
ConcretePrototype1 cp3 = (ConcretePrototype1) cp1.clone();
ConcretePrototype2 cp4 = (ConcretePrototype2) cp2.clone();
cp3.print();
cp4.print();
}
}