Android知识Android开发Android技术知识

原型模式

2017-04-24  本文已影响49人  程序员丶星霖

原型模式

定义

原型模式是一种对象创建型模式,它采取复制原型对象的方法来创建对象的实例。
英文定义:Specify the kinds of objects to create using a prototypical instance , and create new objects by copying this prototype .(用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。)

原型模式的UML类图如下所示

原型模式.jpg

上图中主要涉及一下角色:

原型模式的通用代码如下:

//原型模式通用源码
public class PrototypeClass implements Cloneable{
    //覆写父类Object方法
    @Override
    public PrototypeClass clone(){
        PrototypeClass prototypeClass = null;
        try{
            prototypeClass = (PrototypeClass)super.clone();
        }catch(CloneNotSupportedExecption e){
            //异常处理
        }
        return prototypeClass;
    }
}

优缺点

优点:

缺点:

应用场景:

注意事项

1.构造函数不会被执行

一个实现了Cloneable并重写了clone方法的类,在对象拷贝时构造函数是不会被执行的。

代码如下所示:

public class Thing implements Cloneable{
    public Thing(){
        System.out.println("构造函数被执行了......");
    }
    @Override
    public Thing clone(){
        Thing thing = null;
        try{
            thing = (Thing)super.clone();
        }catch(CloneNotSupportedExecption e){
            e.printStackTrace();
        }
        return thing;
    }
}
public class Client{
    public static void main(String[] args){
        //产生一个对象
        Thing thing = new Thing();
        //拷贝一个对象
        Thing cloneThing = thing.clone();
    }
}
2.浅拷贝和深拷贝

浅拷贝:Object类提供的方法clone只是拷贝本对象,其对象内部的数组、引用对象等都不拷贝,还是指向原生对象的内部元素地址。浅拷贝是对基本数据类型和String类型而言的。

//浅拷贝
public class Thing implements Cloneable{
    //定义一个私有变量
    private ArrayList<String> arrayList = new ArrayList<String>();
    @Override
    public Thing clone(){
        Thing thing = null;
        try{
            thing = (Thing)super.clone();
        }catch(CloneNotSupportedExecption e){
            e.printStackTrace();
        }
        return thing;
    }
    //设置HashMap的值
    public void setValue(String value){
        this.arrayList.add(value);
    }
    //取得ArrayList的值
    public ArrayList<String> getValue(){
        return this.arrayList;
    }
}
//浅拷贝测试
public class Client{
    public static void main(String[] args){
        //产生一个对象
        Thing thing = new Thing();
        //设置一个值
        thing.setValue("张三");
        //拷贝一个对象
        Thing cloneThing = thing.clone();
        cloneThing.setValue("李四");
        System.out.println(thing.getValue());
    }
}

深拷贝:实现完全的拷贝,两个对象之间没有任何的瓜葛。深拷贝是对其他引用类型而言的。

代码如下所示:

//深拷贝
public class Thing implements Cloneable{
    //定义一个私有变量
    private ArrayList<String> arrayList = new ArrayList<String>();
    @Override
    public Thing clone(){
        Thing thing = null;
        try{
            thing = (Thing)super.clone();
            this.arrayList = (ArrayList<String>)this.arrayList.clone();
        }catch(CloneNotSupportedExecption e){
            e.printStackTrace();
        }
        return thing;
    }
    
}

注意:
使用原型模式时,引用的成员变量必须满足两个条件才不会被拷贝:

3.clone与final
欢迎大家关注我的微信公众号
二维码.jpg
上一篇下一篇

猜你喜欢

热点阅读