java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java 原型模式

Java 深入理解创建型设计模式之原型模式

作者:张起灵-小哥

原型(Prototype)模式的定义如下:用一个已经创建的实例作为原型,通过复制该原型对象来创建一个和原型相同或相似的新对象。在这里,原型实例指定了要创建的对象的种类。用这种方式创建对象非常高效,根本无须知道对象创建的细节

1.思考问题

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

按照传统的思路来,我们可能会按照下面的方式去写。

那么这种写法的优缺点自然而然就出来了:

2.什么是原型模式?

原型模式相关的类图如下:

3.克隆羊多莉案例代码(浅拷贝)

这里由于我是新建的普通Java项目,并不是maven项目,所以没法加lombok依赖。那么这里的构造器、setter/getter方法显得这个类的篇幅比较长。。。

package com.szh.prototype.shallowclone;
 
public class Sheep implements Cloneable {
    private String name;
    private Integer age;
    private String color;
    private Sheep friend;
 
    public Sheep(String name, Integer age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }
 
    public Sheep(String name, Integer age, String color, Sheep friend) {
        this.name = name;
        this.age = age;
        this.color = color;
        this.friend = friend;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Integer getAge() {
        return age;
    }
 
    public void setAge(Integer age) {
        this.age = age;
    }
 
    public String getColor() {
        return color;
    }
 
    public void setColor(String color) {
        this.color = color;
    }
 
    public Sheep getFriend() {
        return friend;
    }
 
    public void setFriend(Sheep friend) {
        this.friend = friend;
    }
 
    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                ", friend=" + friend +
                '}';
    }
 
    //克隆该实例,使用默认的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.szh.prototype.shallowclone;
 
public class MainTest {
    public static void main(String[] args) {
        Sheep sheep = new Sheep("多莉",5,"黑白相间",new Sheep("喜羊羊",1,"白色"));
 
        Sheep sheep2 = (Sheep) sheep.clone();
        Sheep sheep3 = (Sheep) sheep.clone();
        Sheep sheep4 = (Sheep) sheep.clone();
        Sheep sheep5 = (Sheep) sheep.clone();
 
        System.out.println(sheep + "  sheep.friend.hashCode = " + sheep.getFriend().hashCode());
        System.out.println(sheep2 + "  sheep2.friend.hashCode = " + sheep2.getFriend().hashCode());
        System.out.println(sheep3 + "  sheep3.friend.hashCode = " + sheep3.getFriend().hashCode());
        System.out.println(sheep4 + "  sheep4.friend.hashCode = " + sheep4.getFriend().hashCode());
        System.out.println(sheep5 + "  sheep5.friend.hashCode = " + sheep5.getFriend().hashCode());
    }
}

从上面的运行结果中可以看到,Sheep类中的前三个成员属性都可以成功的拷贝,但是最后一个friend,它表示羊的朋友(也是Sheep类型,就是引用类型了)。而当我们拷贝完成之后,应该来说都是不一样的新的对象,但是它们中的friend属性的hashCode居然是一样的!!!    这里我们就要来聊一聊深拷贝和浅拷贝了。

浅拷贝:

深拷贝:

4.深拷贝代码案例

package com.szh.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;
    }
 
    @Override
    public String toString() {
        return "DeepCloneableTarget{" +
                "cloneName='" + cloneName + '\'' +
                ", cloneClass='" + cloneClass + '\'' +
                '}';
    }
 
    //因为该类的属性,都是String , 因此我们这里使用默认的clone完成即可
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
package com.szh.prototype.deepclone;
 
import java.io.*;
 
public class DeepPrototype implements Serializable, Cloneable {
 
    public String name; //String 属性
    public DeepCloneableTarget deepCloneableTarget;// 引用类型
 
    public DeepPrototype() {
        super();
    }
 
    @Override
    public String toString() {
        return "DeepPrototype{" +
                "name='" + name + '\'' +
                ", deepCloneableTarget=" + deepCloneableTarget +
                '}';
    }
 
    //深拷贝 - 方式 1 使用clone 方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        deep = super.clone();
        DeepPrototype deepPrototype = (DeepPrototype) deep;
        deepPrototype.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
        return deepPrototype;
    }
 
    //深拷贝 - 方式2 通过对象的序列化实现 (推荐)
    public Object 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 {
                ois.close();
                bis.close();
                oos.close();
                bos.close();
            } catch (Exception e2) {
                System.out.println(e2.getMessage());
            }
        }
    }
}
package com.szh.prototype.deepclone;
 
public class MainTest {
    public static void main(String[] args) throws Exception {
        DeepPrototype prototype = new DeepPrototype();
        prototype.name = "张起灵";
        prototype.deepCloneableTarget = new DeepCloneableTarget("小哥","闷油瓶");
 
        //方式1 完成深拷贝
        DeepPrototype prototype2 = (DeepPrototype) prototype.clone();
        System.out.println("方式1 完成深拷贝");
        System.out.println("prototype.name = " + prototype.name + ", prototype.deepCloneableTarget = " + prototype.deepCloneableTarget);
        System.out.println("prototype.deepCloneableTarget.hashCode = " + prototype.deepCloneableTarget.hashCode());
        System.out.println("-------------------------------------------------------");
        System.out.println("prototype2.name = " + prototype2.name + ", prototype2.deepCloneableTarget = " + prototype2.deepCloneableTarget);
        System.out.println("prototype2.deepCloneableTarget.hashCode = " + prototype2.deepCloneableTarget.hashCode());
        System.out.println("==============================================================================");
 
        //方式2 完成深拷贝
        DeepPrototype prototype3 = (DeepPrototype) prototype.deepClone();
        System.out.println("方式2 完成深拷贝");
        System.out.println("prototype.name = " + prototype.name + ", prototype.deepCloneableTarget = " + prototype.deepCloneableTarget);
        System.out.println("prototype.deepCloneableTarget.hashCode = " + prototype.deepCloneableTarget.hashCode());
        System.out.println("-------------------------------------------------------");
        System.out.println("prototype3.name = " + prototype3.name + ", prototype3.deepCloneableTarget = " + prototype3.deepCloneableTarget);
        System.out.println("prototype3.deepCloneableTarget.hashCode = " + prototype3.deepCloneableTarget.hashCode());
    }
}

5.原型模式总结

到此这篇关于Java 深入理解创建型设计模式之原型模式的文章就介绍到这了,更多相关Java 原型模式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文