设计模式——原型模式(Prototype Pattern)

  原型模式:用原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象。

  UML 图:


原型类:

package com.cnblog.clarck;

/**
 * 原型类
 * 
 * @author clarck
 * 
 */
public abstract class Prototype {
    private String mID;

    public Prototype(String id) {
        mID = id;
    }

    public String getID() {
        return mID;
    }

    public abstract Prototype Clone();
}
具体原型类:

package com.cnblog.clarck;

/**
 * 要想真正拥有克隆的能力,就需要实现Cloneable接口,重写clone方法。通过克隆方法得到的对象得到的是一个本地的副本
 * 
 * @author clarck
 * 
 */
public class ConcreatePrototype1 extends Prototype implements Cloneable {

    public ConcreatePrototype1(String id) {
        super(id);
    }

    @Override
    public Prototype Clone() {
        Prototype protoType = null;
        try {
            protoType = (Prototype) clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        return protoType;
    }
    
}
package com.cnblog.clarck;

/**
 * 要想真正拥有克隆的能力,就需要实现Cloneable接口,重写clone方法。通过克隆方法得到的对象得到的是一个本地的副本
 * 
 * @author clarck
 * 
 */
public class ConcreatePrototype2 extends Prototype implements Cloneable {

    public ConcreatePrototype2(String id) {
        super(id);
    }

    @Override
    public Prototype Clone() {
        Prototype protoType = null;
        try {
            protoType = (Prototype) clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        return protoType;
    }

}
测试类:

package com.cnblog.clarck;

/**
 * 测试类
 * 
 * @author clarck
 * 
 */
public class Client {
    public static void main(String[] args) {
        ConcreatePrototype1 p1 = new ConcreatePrototype1("clarck");
        ConcreatePrototype1 c1 = (ConcreatePrototype1) p1.Clone();
        
        String str = String.format("id:%s", c1.getID());
        System.out.println(str);
        
        ConcreatePrototype1 p2 = new ConcreatePrototype1("clarck2");
        ConcreatePrototype1 c2 = (ConcreatePrototype1) p2.Clone();
        
        String str2 = String.format("id:%s", c2.getID());
        System.out.println(str2);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值