原型模式

原型模式用于对象的克隆通过一个原型,从而克隆出多个相同的对象,解开构造函数的约束
提高性能
缺点 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
我是二号种类
我是三号种类
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值