设计模式23篇:原型模式

定义:

用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。

类图:

这里写图片描述
原型模式浅拷贝:

public class Prototype implements Cloneable {
    public Prototype clone() {
        Prototype prototype = null;
        try {
            prototype = (Prototype) super.clone();
        } catch (CloneNotSupportedException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return prototype;
    }
}
public class ConcretePrototype extends Prototype {
    public void show() {
        System.out.println("原型模式实现类");
    }
}
public class Client {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ConcretePrototype cp = new ConcretePrototype();
        for (int i = 0; i < 10; i++) {
            ConcretePrototype clonecp = (ConcretePrototype)cp.clone();
            clonecp.show();
        }
    }
}

原型模式深拷贝:

public class Person implements Cloneable{
    public String _mname;

    public Person() {
        _mname = "Nick";
    }
    public Person clone() {
        Person _mPerson = null;
        try {
            _mPerson = (Person) super.clone();
            // prototype._mList = this._mList;
        } catch (CloneNotSupportedException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return _mPerson;
    }
}
public class Prototype implements Cloneable {
    Person _mPerson = new Person();
    public Prototype clone() {
        Prototype prototype = null;
        try {
            prototype = (Prototype) super.clone();
            prototype._mPerson = (Person)this._mPerson.clone();
        } catch (CloneNotSupportedException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return prototype;
    }
}
public class Client {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ConcretePrototype cp = new ConcretePrototype();
        for (int i = 0; i < 10; i++) {
            ConcretePrototype clonecp = (ConcretePrototype)cp.clone();
            clonecp.show();
            System.out.println(clonecp._mPerson._mname);
        }
    }
}

注意:

使用原型模式复制对象不会调用类的构造方法。因为对象的复制是通过调用Object类的clone方法来完成的,它直接在内存中复制数据,因此不会调用到类的构造方法,和所有的方法,只clone基本数据类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值