所谓原型模式就是当一个对象在运行时创建后,所有后续的对象都在此对象上通过clone来实现,而不去自己new,set属性的过程。可以简化复杂对象的创建过程。组成的话基本就三个大类:1.原型的抽象类 2.原型的具体实现类 3.具体原型的创建类
原型的抽象类:这个定义了原型的大部分属性及方法,具体类只需要继承该类。这个类需实现Cloneable接口,这样才能调到object.clone()
public abstract class PrototypeProduct implements Cloneable {
private String name;
protected String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
abstract void draw();
public Object clone(){
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
}
写两个具体实现类:
public class PrototypeInstance01 extends PrototypeProduct{
@Override
void draw() {
System.out.println("PrototypeInstance01");
}
}
public class PrototypeInstance02 extends PrototypeProduct{
@Override
void draw() {
System.out.println("PrototypeInstance02");
}
}
写个测试类:
public class Test {
public static void main(String[] args) {
PrototypeInstance01 prototypeInstance01 = new PrototypeInstance01();
PrototypeInstance02 prototypeInstance02 = new PrototypeInstance02();
PrototypeProduct prototypeProduct1 = (PrototypeProduct) prototypeInstance01.clone();
prototypeProduct1.draw();
PrototypeProduct prototypeProduct2 = (PrototypeProduct) prototypeInstance02.clone();
prototypeProduct2.draw();
}
}
这样写法就相当于我子类实现只new一次,后续都可以通过父类引用来指向子类,调用子类的clone方法。获取一个一模一样的对象。那么问原型模式有什么用,就比如复杂对象你set属性需要很多参数,这个对象你用于另外场景又要set一遍。这样的话就可以直接clone方便一些。不过企业级中一般会有redis做全局缓存。所以只需要理解这个思想就行。