设计模式——原型模式

什么是原型模式

简单来说就是对象的拷贝,拷贝分为深拷贝和浅拷贝

深拷贝:两个变量代表不同的内存区域,但值完全相同

浅拷贝:拷贝地址,两个变量代表同一块内存区域

在原型模式中,对象的拷贝的基本数据类型及String是深拷贝,但是引用类型根据需要,可以是浅拷贝,也可以是深拷贝

 

java中的等号(=)对于基本数据类型及其封装类、String来说是深拷贝,对于对象来说是浅拷贝

 

原型模式的角色

Prototype:抽象原型角色,声明克隆方法

ConcretePrototype:具体原型角色,实现克隆角色,返回一个全新的克隆对象

Client:客户端

 

我们先来看看对于引用使用浅拷贝:

something类

public class something {
    
    private int index;
    
    public something(int index){
        this.index=index;
    }
    
    public void setIndex(int index){
        this.index=index;
    }
    
    public int getIndex(){
        return this.index;
    }
    
}

Prototype:

public interface Prototype {
    Prototype clone();
}

ConcreteProtype:

public  class ConcretePrototype implements Prototype{

    private something deal;
    private int prototy;

    public int getPrototy() {
        return prototy;
    }

    public void setPrototy(int prototy) {
        this.prototy = prototy;
    }
    
    public void setDeal(something deal){
        this.deal=deal;
    }
    
    public something getDeal(){
        return deal;
    }
    
    @Override
    public Prototype clone() {
        ConcretePrototype temp=new ConcretePrototype();
        temp.setPrototy(prototy);
        temp.setDeal(deal);
        return temp;
    }
    
}

main:

public class main {
    public static void main(String[] args){
        ConcretePrototype temp=new ConcretePrototype();
        temp.setDeal(new something(1));
        temp.setPrototy(1);
        
        ConcretePrototype Clone=(ConcretePrototype)temp.clone();
        
        Clone.getDeal().setIndex(0);
        System.out.println("Clone的index值为:"+Clone.getDeal().getIndex()+" temp的index值为:"+temp.getDeal().getIndex());
        
        Clone.setPrototy(2);
        System.out.println("Clone的deal的index值为:"+Clone.getPrototy()+" temp的deal的index值为:"+temp.getPrototy());
    }
}

执行结果:

对于基本数据类型,java的=号是深拷贝,对于引用类型,使用的是浅拷贝

 

对于引用使用深拷贝,更改ConcreteProtype:

public  class ConcretePrototype implements Prototype{

    private something deal;
    private int prototy;

    public int getPrototy() {
        return prototy;
    }

    public void setPrototy(int prototy) {
        this.prototy = prototy;
    }
    
    public void setDeal(something deal){
        this.deal=deal;
    }
    
    public something getDeal(){
        return deal;
    }
    
    @Override
    public Prototype clone() {
        ConcretePrototype temp=new ConcretePrototype();
        temp.setPrototy(prototy);
        temp.setDeal(new something(deal.getIndex()));
        return temp;
    }
    
}

执行结果:

 

对于大对象的深拷贝往往会导致代码十分复杂(需要复制的值太多),java的Object类有一个clone方法,为了使用它,我们需要继承Cloneable接口,这个接口的作用是通知JVM在运行时可以安全的对此类的对象进行拷贝,值得注意的是,Object类的clone方法对于引用类型是浅拷贝

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值