六、原型模式

原型模式

**当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。
**

原型模式主要就是通过clone方式来创建对象,不需要每次new,这样会多次调用构造方法,次数多了之后影响效率。

原型模式比较简单,就不写具体demo代码了,主要的就是涉及到浅复制和深复制的问题。

浅复制:具体来说就是只是复制引用,直接用clone就是浅复制。

深复制如下:

test demo类:

public class Test implements Cloneable{
    private String test;

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    
}
public class Resume implements Cloneable {
    private String name;
    private String sex;
    private Test test = new Test(); 
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Test getTest() {
        return test;
    }

    public void setTest(Test test) {
        this.test = test;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Resume resume = (Resume)super.clone();
        return resume;
    }

}

main测试代码如下:

public class Main {

    /**
     * @param args
     * @throws CloneNotSupportedException 
     */
    public static void main(String[] args) throws CloneNotSupportedException {
        Resume resume1 = new Resume();
        Resume resume2 = (Resume)resume1.clone();
        System.out.println(resume1.hashCode() + " " + resume2.hashCode());
        System.out.println(resume1.getTest().hashCode() + " " + resume2.getTest().hashCode());
    }

}

因为里面存在了除了基本类型String还存在了test,且test实现了Cloneable接口,实现clone方法,这个就是深复制。

如果要把上面的代码改成浅复制,只需要把test类改成一个空的类就是浅复制。

原型模式比较简单,在此不多做详细介绍。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值