原型模式:用原型实例指定对象的种类,并且通过拷贝这些原型对象创建新的对象;
原型模式主要包含三个:抽象原型类,具体原型类,客户端,从类图中可以看出抽象原型类中有一个Clone接口方法,后面的具体原型类通过实现这个接口来复制自身。其实原型模式就是通过克隆来实现。以下通过代码来体现一下;
ProtoType 接口:
public interface Prototype extends Cloneable{
Prototype clone();
}
ConcretePrototypeA 类
public class ConcretePrototypeA implements Prototype{
private String property;
public ConcretePrototypeA(String property) {
this.property = property;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
@Override
public Prototype clone() {
try {
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
}
client 类:
import org.junit.Test;
import junit.framework.Assert;
public class Client {
@Test
public void prototypeTest() throws CloneNotSupportedException {
ConcretePrototypeA prototype = new ConcretePrototypeA("aaa");
ConcretePrototypeA prototype1 = (ConcretePrototypeA) prototype.clone();
Assert.assertEquals("aaa", prototype.getProperty());
Assert.assertEquals("aaa", prototype1.getProperty());
prototype1.setProperty("bbb");
Assert.assertEquals("aaa", prototype.getProperty());
Assert.assertEquals("bbb", prototype1.getProperty());
}
}
“`
以上为原型模式示例代码;其实其根本就是实现类的克隆;而如果在ConcretePrototypeA 类中涉及到了对象的复制,又会有深拷贝的概念,如果不知道什么使深拷贝和浅拷贝,大家去搜一下吧,这里就不做详解了