设计模式-原型模式

设计模式-原型模式

简单方式实现:

public class Sheep {
    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  void setName(String name){
        this.name=name;
    }

    public String getName(){
        return name;
    }

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

    public int getAge(){
        return age;
    }

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

    public String getColor(){
        return color;
    }

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

客户端

public class Client {
    public static void main(String[] args) {
        Sheep sheep = new Sheep("tom", 1, "白色");

        Sheep sheep1 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
        Sheep sheep2 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
        Sheep sheep3 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());

        System.out.println(sheep1);
        System.out.println(sheep2);
        System.out.println(sheep3);

    }
}

传统的方式的优缺点

  1. 优点是比较好理解,简单易操作
  2. 在创建新的对象时,总是需要获取原对象的属性。如果创建的对象比较复杂,这样就会效率低下。
  3. 总是重新获取对象,而不是动态获取对象运行时的状态,不够灵活

改进思路

java中Object类是所有类的根类,Object类提供了一个clone()方法。
该方法可以将一个Java对象复制一份,但是需要实现clone的java类必须要实现一个接口Cloneable,
该接口表示该类能够复制且具有复制的能力

原型模式-基本介绍

  1. 原型模式是指:用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象
  2. 原型模式是一种创建型设计模式,允许一个对象再创建另一个定制的对象,无需知道如何创建新的细节
  3. 工作原理:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝他们自己来实施创建,即对象.clone();

原型模式原理结构图-uml类型

在这里插入图片描述
)]

使用原型模式解决克隆问题

public class Sheep implements Cloneable{
    private String name;

    private int age;

    private String color;

    private String address="蒙古羊";

    public Sheep friend;//是对象,克隆是会如何处理

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

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

    public String getName(){
        return 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 + '\'' +
                ", address='" + address + " '}'";
    }

    @Override
    protected Sheep clone() throws CloneNotSupportedException {

        Sheep sheep=null;

        try {
           sheep=(Sheep)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        return sheep;
    }
}

使用客户端

public class Client {
    public static void main(String[] args) throws CloneNotSupportedException {
        Sheep sheep = new Sheep("tom",1,"白色");

        sheep.friend = new Sheep("jack",2,"黑色");

        Sheep clone = (Sheep)sheep.clone();

        System.out.println(clone.friend.hashCode());
        System.out.println(sheep.friend.hashCode());
    }
}

深入讨论-浅拷贝和深拷贝

  • 浅拷贝介绍

对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象

对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组、某个类的对象等。那么浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制一个给新的对象。在这种情况下,在一个对象中修改该成员变量会影响新克隆对象的成员变量值

  • 浅拷贝是使用默认的clone()方法来实现

sheep=(Sheep)super.clone();

  • 深拷贝介绍

复制对象的所有基本数据类型的成员变量值

为所有引用数据类型的成员变量申请存储空间,并复制每个引用数据类型成员变量所引用的对象,直到该对象可达的所有对象。也就是说,对象进行深拷贝要对整个对象(包括对象的引用类型)进行拷贝

  • 深拷贝实现

重写clone方法来实现拷贝

通过对象序列化实现深拷贝(推荐)

深拷贝实现

在这里插入图片描述

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
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "DeepCloneableTarget{" +
                "cloneName='" + cloneName + '\'' +
                ", cloneClass='" + cloneClass + '\'' +
                '}';
    }
}
public class DeepProtoType implements Serializable, Cloneable {
    public String name;

    public DeepCloneableTarget deepCloneableTarget;

    public DeepProtoType() {
        super();
    }

    public String getName() {
        return name;
    }

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

    public DeepCloneableTarget getDeepCloneableTarget() {
        return deepCloneableTarget;
    }

    public void setDeepCloneableTarget(DeepCloneableTarget deepCloneableTarget) {
        this.deepCloneableTarget = deepCloneableTarget;
    }

    /**
     * 第一种方法
     *
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {

        Object deep = null;

        deep = super.clone();

        //对引用类型的属性,进行单独处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;

        deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();

        return deepProtoType;
    }


    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{
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            }catch(Exception e2){
                System.out.println(e2.getMessage());
            }
        }
    }


    @Override
    public String toString() {
        return "DeepProtoType{" +
                "name='" + name + '\'' +
                ", deepCloneableTarget=" + deepCloneableTarget +
                '}';
    }
}

客户端

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

        deepProtoType.setDeepCloneableTarget(new DeepCloneableTarget("qwe","asd"));

        //第一种
        DeepProtoType clone =(DeepProtoType) deepProtoType.clone();

        System.out.println(deepProtoType);
        System.out.println(deepProtoType.getDeepCloneableTarget().hashCode());
        System.out.println(deepProtoType.hashCode());

        System.out.println("============第一种=============");
        System.out.println(clone);
        System.out.println(clone.getDeepCloneableTarget().hashCode());
        System.out.println(clone.hashCode());
        System.out.println();



        //第二种
        DeepProtoType deepClone =(DeepProtoType) deepProtoType.deepClone();
        System.out.println("============第二种=============");
        System.out.println(deepClone);
        System.out.println(deepClone.getDeepCloneableTarget().hashCode());
        System.out.println(deepClone.hashCode());

    }
}

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

  • 创建新的对象比较复杂时,可以利用原型模式简化的创建过程,同时也能够提高效率
  • 不用重新初始化对象,而是动态地获取对象运行时的状态
  • 如果原始对象发生变化(增加或者减少属性),其它克隆对象的也会发生相应的变化,无需修改代码
  • 在实现深克隆的时候可能需要比较复杂的代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值