原型模式用于对象的克隆通过一个原型,从而克隆出多个相同的对象,解开构造函数的约束
提高性能
缺点 1、配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候。 2、必须实现 Cloneable 接口。
类似于血族的场景
有一个主人master 能够生产出大量的奴隶,这些奴隶分为三种类型
通过池生产出这些奴隶的复制品。
//创建master 代码
public abstract class Master implements Cloneable{
private String id;
public String getId() {
return id;
}
abstract void sayName();
public void setId(String id) {
this.id = id;
}
@Override
protected Master clone() {
Master master=null;
try {
master = (Master)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return master;
}
}
//不同奴隶的代码
public class Slave extends Master{
@Override
void sayName() {
System.out.println("我是一号种类");
}
}
public class Slave2 extends Master{
@Override
void sayName() {
System.out.println("我是二号种类");
}
}
public class Slave3 extends Master{
@Override
void sayName() {
System.out.println("我是三号种类");
}
}
//池
public class MasterCache {
private static Map<String,Master> cache =new HashMap<>();
public static Master getClone(String key){
Master pro = cache.get(key);
return pro.clone();
}
static final MasterCache proche=new MasterCache();
private MasterCache() {
cache.put("1",new Slave());
cache.put("2",new Slave2());
cache.put("3",new Slave3());
}
}
//测试
public class TestDemo {
public static void main(String[] args) {
Master s1 =MasterCache.getClone("1");
s1.sayName();
Master s1_c =MasterCache.getClone("1");
s1_c.sayName();
System.out.println(s1==s1_c);
Master s2 = MasterCache.getClone("2");
s2.sayName();
Master s3 = MasterCache.getClone("2");
s3.sayName();
}
}
-----------out--------------
我是一号种类
我是一号种类
false
我是二号种类
我是三号种类