Java设计模式——原型模式(实例)

1、克隆羊问题

现有一只羊,姓名:tom,年龄:1,颜色:白色。克隆10只属性完全相同的羊

2、传统方式实例

Sheep

package com.weirdo.prototype;

public class Sheep {

    private String name;
    private int age;
    private String color;

    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;
    }
}

Client

package com.weirdo.prototype;

import com.alibaba.fastjson.JSONObject;

public class Client {

	public static void main(String[] args) {
		//传统的方法
		Sheep sheep1 = new Sheep("tom",1,"白色");

		Sheep sheep2 = new Sheep(sheep1.getName(),sheep1.getAge(),sheep1.getColor());
		Sheep sheep3 = new Sheep(sheep1.getName(),sheep1.getAge(),sheep1.getColor());
		Sheep sheep4 = new Sheep(sheep1.getName(),sheep1.getAge(),sheep1.getColor());
		Sheep sheep5 = new Sheep(sheep1.getName(),sheep1.getAge(),sheep1.getColor());
		//....

		System.out.println("sheep1:"+JSONObject.toJSONString(sheep1));
		System.out.println("sheep2:"+JSONObject.toJSONString(sheep2));
		System.out.println("sheep3:"+JSONObject.toJSONString(sheep3));
		System.out.println("sheep4:"+JSONObject.toJSONString(sheep4));
		System.out.println("sheep5:"+JSONObject.toJSONString(sheep5));
		//...
	}
}

3、传统方式优缺点

优点

  • 好理解,无脑操作,啪啪啪。

缺点

  • 在创建新对象时,总是需要重新获取原始对象的属性,如果创建的对象属性比较多时就贼麻烦。
  • 总是重新初始化对象,而不是动态获取对象运行时的状态,不灵活。

改进思路

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

4、原型模式基本介绍

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

5、原型模式解决克隆羊问题实例(浅拷贝)

Sheep

package com.weirdo.prototype.improve;

public class Sheep implements Cloneable{

    private String name;
    private Integer age;
    private String color;

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

    @Override
    protected Object clone() {
        Object obj = null;
        try {
            obj = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return obj;
    }

    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;
    }
}

Client

package com.weirdo.prototype.improve;

import com.alibaba.fastjson.JSONObject;

public class Client {

	public static void main(String[] args) {
		System.out.println("原型模式完成对象的创建");

		Sheep sheep1 = new Sheep("tom", 1, "白色");

		//克隆
		Sheep sheep2 = (Sheep)sheep1.clone();
		Sheep sheep3 = (Sheep)sheep1.clone();
		Sheep sheep4 = (Sheep)sheep1.clone();
		Sheep sheep5 = (Sheep)sheep1.clone();

		System.out.println("sheep1=" + JSONObject.toJSONString(sheep1));
		System.out.println("sheep2=" + JSONObject.toJSONString(sheep2));
		System.out.println("sheep3=" + JSONObject.toJSONString(sheep3));
		System.out.println("sheep4=" + JSONObject.toJSONString(sheep4));
		System.out.println("sheep5=" + JSONObject.toJSONString(sheep5));
	}
}

6、浅拷贝与深拷贝

6.1 浅拷贝
  • 对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象。
  • 对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组、某个类的对象等,那么浅拷贝会进行
    引用传递,也就是只是将该成员变量的引用值(内存地址)复制一份给新的对象。因为实际上两个对象的该成员变量都指向同一个实例。在这种情况下,在一个对象中修改该成员变量会影响到另一个对象的该成员变量值。
  • 浅拷贝是使用默认的clone()方法来实现的,即sheep=(Sheep)super.clone();
  • 以上克隆羊实例便是使用的浅拷贝
6.2 深拷贝
  • 复制对象的所有基本数据类型的成员变量值
  • 为所有引用数据类型的成员变量申请存储空间,并复制每个引用数据类型成员变量所引用的对象,直到该对象可达的所有对象。也就是说,对象进行深拷贝要对整个对象(包括对象的引用类型)进行拷贝
  • 深拷贝实现方式1:重写clone方法来实现深拷贝
  • 深拷贝实现方式2:通过对象序列化实现深拷贝(推荐)

7、浅拷贝实例

以上克隆羊的实例就是浅拷贝,但是不适合论证浅拷贝拷贝的是引用地址。

因为Sheep中的属性,age拷贝的是值,改变其大小不回影响拷贝后属性,name和color都是引用类型,无法改变其内容。

以下将详细论证浅拷贝,对于基本类型来说拷贝的是值,对于其他类型的数据来说拷贝的是引用地址。

Sheep

package com.weirdo.prototype.shallowClone;

public class Sheep implements Cloneable{

    private String name;
    private int age;
    private String color;
    private SheepWeight sheepWeight;

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

    @Override
    protected Object clone() {
        Object obj = null;
        try {
            obj = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return obj;
    }

    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;
    }

    public SheepWeight getSheepWeight() {
        return sheepWeight;
    }

    public void setSheepWeight(SheepWeight sheepWeight) {
        this.sheepWeight = sheepWeight;
    }
}

SheepWeight

package com.weirdo.prototype.shallowClone;

public class SheepWeight {
    private int sheepWeight;

    public SheepWeight (int sheepWeight){
        this.sheepWeight = sheepWeight;
    }

    public int getSheepWeight() {
        return sheepWeight;
    }

    public void setSheepWeight(int sheepWeight) {
        this.sheepWeight = sheepWeight;
    }
}

Client

package com.weirdo.prototype.shallowClone;

import com.alibaba.fastjson.JSONObject;

public class Client {

	public static void main(String[] args) {
		System.out.println("浅拷贝实例");
		//tom的体重
		SheepWeight sheepWeight = new SheepWeight(20);
		//new一个羊,并设置它的体重和其它属性
		Sheep sheep1 = new Sheep("tom", 1, "白色",sheepWeight);

		//开始拷贝
		Sheep sheep2 = (Sheep)sheep1.clone();
		Sheep sheep3 = (Sheep)sheep1.clone();
		Sheep sheep4 = (Sheep)sheep1.clone();
		Sheep sheep5 = (Sheep)sheep1.clone();

		System.out.println("sheep1=" + JSONObject.toJSONString(sheep1));
		System.out.println("sheep2=" + JSONObject.toJSONString(sheep2));
		System.out.println("sheep3=" + JSONObject.toJSONString(sheep3));
		System.out.println("sheep4=" + JSONObject.toJSONString(sheep4));
		System.out.println("sheep5=" + JSONObject.toJSONString(sheep5));

		System.out.println("去了一年非洲,tom吃胖了,颜色也变了");

		//改变sheepWeight,sheepWeight属性在SheepWeight类中是一个基本类型,但在Sheep类中则是一个引用地址
		//此时改变SheepWeight中的sheepWeight属性值,对于Sheep类来说引用地址不变但值变了,因此拷贝之后的属性也将跟着改变
		sheepWeight.setSheepWeight(40);

		//浅拷贝对于基本类型是直接拷贝的值,因此拷贝之后的属性不会跟着改变
		sheep1.setAge(2);

		//此处表面上看是改变了原型的color属性值,但实际上是改变了原型color的引用地址(无法改变String类型的内容)
		//由于浅拷贝对于String类型是拷贝的引用地址,因此改变原型的color的引用地址,拷贝后的color引用地址不会变,也即拷贝后的color属性仍是指向“白色”的地址
		sheep1.setColor("黑色");

		//如果用一下方式改变原型的sheepWeight属性值,则拷贝后的数据不会受到影响,因为以下方式是改变了Sheep中对于sheepWeight的引用地址
		//sheep1.setSheepWeight(new SheepWeight(45));

		System.out.println("sheep1=" + JSONObject.toJSONString(sheep1));
		System.out.println("sheep2=" + JSONObject.toJSONString(sheep2));
		System.out.println("sheep3=" + JSONObject.toJSONString(sheep3));
		System.out.println("sheep4=" + JSONObject.toJSONString(sheep4));
		System.out.println("sheep5=" + JSONObject.toJSONString(sheep5));
	}
}

运行结果

在这里插入图片描述

8、深拷贝实例

8.1 重写clone方法来实现深拷贝

Person

package com.weirdo.prototype.deepClone;

public class Person implements Cloneable {
    private String name;
    private int age;
    private String sex;
    private Weight weight;

    public Person(String name, int age, String sex, Weight weight) {
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.weight = weight;
    }

    public int getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

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

    public Weight getWeight() {
        return weight;
    }

    public void setWeight(Weight weight) {
        this.weight = weight;
    }

    /**
     * 深拷贝 - 方式1 通过重写clone方法来实现
     * @return
     */
    @Override
    protected Object clone() {
        Person person = null;
        try {
            person = (Person)super.clone();
            //对于引用类型单独处理
            person.setWeight((Weight) weight.clone());
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return person;
    }
}

Weight

package com.weirdo.prototype.deepClone;

import java.io.Serializable;

public class Weight implements Cloneable, Serializable {

    private int weight;

    public Weight(int weight){
        this.weight = weight;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    @Override
    protected Object clone() {
        Weight weight = null;
        try {
            weight = (Weight)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return weight;
    }
}

Client

package com.weirdo.prototype.deepClone;

import com.alibaba.fastjson.JSONObject;

public class Client {

	public static void main(String[] args) throws CloneNotSupportedException {

		//方式1:重写clone方法来实现深拷贝
		Weight personWeight = new Weight(120);
		Person person1 = new Person("小明",18,"男",personWeight);
		Person person2 = (Person) person1.clone();
		System.out.println("方式1:重写clone方法来实现深拷贝");
		System.out.println("person1:"+ JSONObject.toJSONString(person1));
		System.out.println("person2:"+ JSONObject.toJSONString(person2));
		System.out.println("小明去了一趟泰国,一年后...");
		person1.setAge(19);
		person1.setSex("女");
		personWeight.setWeight(95);
		System.out.println("person1:"+ JSONObject.toJSONString(person1));
		System.out.println("person2:"+ JSONObject.toJSONString(person2)+"------------>深拷贝,拷贝后的数据不受原来属性变更影响");
	}
}

运行结果

在这里插入图片描述

8.2 通过对象序列化实现深拷贝

Dog

package com.weirdo.prototype.deepClone;

import java.io.*;

public class Dog implements Serializable {
    private String name;
    private int age;
    private String sex;
    private Weight weight;

    public Dog(String name,int age,String sex,Weight weight){
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.weight = weight;
    }

    public int getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

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

    public Weight getWeight() {
        return weight;
    }

    public void setWeight(Weight weight) {
        this.weight = weight;
    }

    /**
     * 深拷贝 - 方式2 通过对象的序列化实现 (推荐)
     * @return
     */
    public Dog serializableClone() {
        //创建流对象
        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);
            Dog copyObj = (Dog)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());
            }
        }
    }
}

Weight

package com.weirdo.prototype.deepClone;

import java.io.Serializable;

public class Weight implements Cloneable, Serializable {

    private int weight;

    public Weight(int weight){
        this.weight = weight;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    @Override
    protected Object clone() {
        Weight weight = null;
        try {
            weight = (Weight)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return weight;
    }
}

Client

package com.weirdo.prototype.deepClone;

import com.alibaba.fastjson.JSONObject;

public class Client {

	public static void main(String[] args) throws CloneNotSupportedException {

		//方式2:通过序列化来实现深拷贝
		Weight dogWeight = new Weight(40);
		Dog dog1 = new Dog("大黄",1,"公",dogWeight);
		Dog dog2 = dog1.serializableClone();
		System.out.println("方式2:通过序列化来实现深拷贝");
		System.out.println("dog1:"+ JSONObject.toJSONString(dog1));
		System.out.println("dog2:"+ JSONObject.toJSONString(dog2));
		System.out.println("大黄去了一趟泰国,一年后...");
		dog1.setAge(2);
		dog1.setSex("母");
		dogWeight.setWeight(35);
		System.out.println("dog1:"+ JSONObject.toJSONString(dog1));
		System.out.println("dog2:"+ JSONObject.toJSONString(dog2)+"------------>深拷贝,拷贝后的数据不受原来属性变更影响");
	}
}

运行结果

在这里插入图片描述

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

  • 创建新对象比较复杂是,可以利用原型模式简化对象的创建过程,同时也能提高效率
  • 不用重新初始化对象,而是动态地获得对象运行时的状态
  • 如果原始对象发生变化,其它克隆对象也会发生相应的变化,无需修改代码
  • 在实现深克隆时可能需要比较复杂的代码
  • 缺点:需要为每一个类配备一个克隆方法,这对全新的类来说不是很难。但对已有的类进行改造时,需要修改其源代码,违背了开闭原则(OCP)。
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只小熊猫呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值