设计模式之原型模式

原型模式解决克隆羊问题

有一只羊 姓名为:tom,年龄为:1,颜色为:白色,请编写程序创建和tom属性完全相同的十只羊

image

Prototype:原型类,声明一个克隆自己的接口
ConcretePrototype:具体的原型类,实现一个克隆自己的操作
Client:让一个原型对象克隆自己,从而创建一个新的对象(属性一样)

代码实现:

package com.cedric.prototype;

public class Sheep implements Cloneable{
    private String name;
    private int age;
    private String color;

    public Sheep(){

    }

    public Sheep(String name,int age,String color){
        this.name = name;
        this.age = age;
        this.color = color;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }

    // 克隆该实例,使用默认的clone方法来完成
    @Override
    protected Object clone(){
        Sheep sheep = null;
        try {
            sheep = (Sheep)super.clone();
        } catch (CloneNotSupportedException e) {
            System.out.println(e.getMessage());
        }

        return sheep;
    }
}
package com.cedric.prototype;

public class Client {
    public static void main(String[] args) {
        System.out.println("原型模式完成对象的创建");
        Sheep sheep = new Sheep("tom",1,"白色");
        Sheep sheep1 = (Sheep) sheep.clone();
        Sheep sheep2 = (Sheep) sheep.clone();
        Sheep sheep3 = (Sheep) sheep.clone();
        Sheep sheep4 = (Sheep) sheep.clone();
        Sheep sheep5 = (Sheep) sheep.clone();

        System.out.println(sheep);
        System.out.println(sheep1);
        System.out.println(sheep2);
        System.out.println(sheep3);
        System.out.println(sheep4);
        System.out.println(sheep5);
    }
}

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

原型模式默认是浅拷贝

深拷贝

1.复制对象的所有基本数据类型的成员变量值
2.对象进行深拷贝要对整个对象(包括对象的引用类型)进行拷贝

重写clone方法实现深拷贝

package com.cedric.prototype.deepclone;

import java.io.Serializable;

public class DeepCloneableTarget implements Serializable,Cloneable{

    private static final long serialVersionUID = 1L;

    private String cloneName;

    private String cloneClass;


    public  DeepCloneableTarget(String cloneName,String cloneClass){
        this.cloneName = cloneName;
        this.cloneClass = cloneClass;
    }

    public String getCloneName() {
        return cloneName;
    }

    public void setCloneName(String cloneName) {
        this.cloneName = cloneName;
    }

    public String getCloneClass() {
        return cloneClass;
    }

    public void setCloneClass(String cloneClass) {
        this.cloneClass = cloneClass;
    }

    // 因为该类的属性都是String,因此使用默认的clone完成即可
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

使用序列化实现深拷贝

package com.cedric.prototype.deepclone;

import java.io.*;

public class DeepProtoType implements Serializable,Cloneable{

    public String name;
    public DeepCloneableTarget deepCloneableTarget; // 引用
    public DeepProtoType(){

    }

    // 深拷贝 - 方式1 使用clone方法

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        // 这里完成对基本数据类型(属性)和String的克隆
        deep = super.clone();
        // 对引用类型的属性进行单独处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();

        return deepProtoType;
    }

    // 深拷贝 - 方式2 通过对象的序列化实现

    public DeepProtoType deepClone(){
        // 创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {

            // 序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this); //当前这个对象以对象流方式输出

            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType copyObj = (DeepProtoType) ois.readObject();

            return copyObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭流
            try{
                if(bos != null){
                    bos.close();
                }
            } catch (Exception e){
                e.printStackTrace();
            }

            try{
                if(oos != null){
                    oos.close();
                }
            } catch (Exception e){
                e.printStackTrace();
            }

            try{
                if(bis != null){
                    bis.close();
                }
            } catch (Exception e){
                e.printStackTrace();
            }

            try{
                if(ois != null){
                    ois.close();
                }
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

Client

package com.cedric.prototype.deepclone;

public class Client {
    public static void main(String[] args) throws CloneNotSupportedException {
        DeepProtoType deepProtoType = new DeepProtoType();
        deepProtoType.name = "张三";

        deepProtoType.deepCloneableTarget = new DeepCloneableTarget("李四","李五");

        // 方式1 完成深拷贝
       /* DeepProtoType deepProtoType1 = (DeepProtoType) deepProtoType.clone();
        System.out.println(deepProtoType.name + deepProtoType.hashCode());
        System.out.println(deepProtoType1.name + deepProtoType1.hashCode());*/


        // 方式2 完成深拷贝
        DeepProtoType deepProtoType1 = (DeepProtoType) deepProtoType.clone();
        System.out.println(deepProtoType.name + deepProtoType.hashCode());
        System.out.println(deepProtoType1.name + deepProtoType1.hashCode());

    }
}

原型模式的注意事项和细节

1.创建新的对象比较复杂时,可以利用原型模式简化对象的创建过程,同时也能够提高效率
2.不用重新初始化对象,而是动态获得对象运行时的状态
3.如果原始对象发生变化(增加或减少属性),其他克隆对象也会发生相应的变化,无需修改代码
4.在实现深克隆的时候可能需要比较复杂的代码
5.缺点:需要为每一个类配备一个克隆方法,这对全新的类来说不是很难,但对已有的类进行改造时,需要
修改其源代码,违背了OCP原则
posted @ 2021-10-10 16:40  guided  阅读(30)  评论(0)    收藏  举报