设计模式之Prototype模式

本文深入探讨了Prototype模式,一种通过复制现有实例来生成新实例的设计模式。该模式避免了指定类名生成实例,提供了灵活的实例创建方式。文章详细介绍了Prototype模式的角色构成,包括Prototype、ConcretePrototype和Client,并通过具体代码示例展示了如何实现和使用Prototype模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Prototype模式

​ 根据实例原型,实例模型来生成新的实例 ,通过复制来生成实例

  1. 不指定类名的前提下生成实例

  2. 根据现有的实例来生成新的实例

    clone Cloneable

出场角色

  1. Prototype(原型)

    定义用于复制现有实例来生成新实例的方法

  2. ConcretePrototype(具体的原型)

    实现复制现有实例并生成新实例的方法

  3. Client(使用者)

    使用复制实例的方法生成新的实例

    interface Product extends Clonable{
        public abstract void use(String s);
        public abstract Product createClone();
    }
    class Manager{
        private HashMap showcase = new HashMap();
        public void register(String name,Product proto){
    		shwocase.put(name,proto);
        }
        public Product create(String protoname){
            Product p = (Product) showcase.get(protoname);
            return p.createClone();
        }
    }
    
    class MessageBox implements Product{
    	private char decochar;
        public MessageBox(char decochar){
            this.decochar = decochar;
        }
        public void use(String s){
            int length = s.getBytes().length;
            for(int i = 0 ; i < length + 4; i++){
    			System.out.print(decochar);
            }
            System.out.println("");
            System.out.println(decochar +" " +s+" " + decochar);
            for(int i = 0 ;i<length+4;i++){
    			System.out.print(decochar);
            }
            System.out.println("");
        }
        
        public Product createClone(){
    		Product p = null;
            try{
                //clone
    			p=(Product)clone();                           
            }catch(CloneNotSupportedException e){
                e.printStackTeace();
            }
            return p;
        }
    }
    
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值