java设计模式--原型模式详解


Posted in Java/Android onJuly 21, 2021

引例

问题:

现在有一只羊(包含属性:名字Dolly、年龄2),需要克隆10只属性完全相同的羊。

一般解法:

定义Sheep类表示羊,包括构造器、getter()和toString()。

public class Sheep {
    private String name;
    private int age;
    public Sheep(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

在客户端实例化多利,然后再根据多利的属性去实例化10只羊。

public class Client {
    public static void main(String[] args) {
        Sheep sheepDolly=new Sheep("Dolly",2);
        Sheep sheep1 = new Sheep(sheepDolly.getName(), sheepDolly.getAge());
        Sheep sheep2 = new Sheep(sheepDolly.getName(), sheepDolly.getAge());
        Sheep sheep3 = new Sheep(sheepDolly.getName(), sheepDolly.getAge());
        //....
        System.out.println(sheep1+",hashCode:"+sheep1.hashCode());
        System.out.println(sheep2+",hashCode:"+sheep2.hashCode());
        System.out.println(sheep3+",hashCode:"+sheep3.hashCode());
        //...
    }
}

运行结果

java设计模式--原型模式详解

优缺点:

这种方法是我们首先很容易就能想到的,也是绝大多数人的第一做法。

但缺点也很明显,每次创建新对象时需要获取原始对象的属性,对象复杂时效率很低;此外不能动态获得对象运行时的状态,若类增减属性需要改动代码。

下面我们看下原型模式的解法。

原型模式

原型模式(Prototype Pattern)是一种创建型设计模式,允许一个对象再创建另外一个可定制的对象,无需知道如何创建的细节。即用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象。

工作原理:将原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。即用基类Object的clone()方法或序列化。

UML类图:

java设计模式--原型模式详解

  • Prototype:原型类,声明一个克隆自己的接口
  • ConcretePrototype: 具体的原型类, 实现一个克隆自己的操作
  • Client: 客户端让一个原型对象克隆自己,从而创建一个新的对象

原型模式又可分为浅拷贝和深拷贝,区别在于对引用数据类型的成员变量的拷贝,小朋友你是否有很多问号? 不急 ,看完这两种方法实现你就懂了。

浅拷贝

在原先Sheep类基础上实现Cloneable接口,重写clone方法。

public class Sheep implements Cloneable{
    private String name;
    private int age;
    @Override
    protected Object clone()  {//克隆该实例,使用默认的clone方法来完成
        Sheep sheep = null;
        try {
            sheep = (Sheep)super.clone();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return sheep;
    }
    public Sheep(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

客户端调用

public class Client {
    public static void main(String[] args) {
        Sheep sheepDolly=new Sheep("Dolly",2);
        Sheep sheep1 = (Sheep)sheepDolly.clone();
        Sheep sheep2 = (Sheep)sheepDolly.clone();
        Sheep sheep3 = (Sheep)sheepDolly.clone();
        //....
        System.out.println("sheep1:"+sheep1+",hashCode:" + sheep1.hashCode());
        System.out.println("sheep2:"+sheep2+",hashCode:" + sheep2.hashCode());
        System.out.println("sheep3:"+sheep3+",hashCode:" + sheep3.hashCode());
        //...
    }
}

运行结果

java设计模式--原型模式详解

至此,原型模式的浅拷贝也成功克隆了三个对象,但是看进度条发现并不简单。

现在小羊有了一个朋友小牛,Sheep类添加了一个引用属性Cow,我们同样再克隆一遍。

Sheep类

public class Sheep implements Cloneable{
    private String name;
    private int age;
    public Cow friend;//新朋友Cow对象,其余不变
    @Override
    protected Object clone()  {
        Sheep sheep = null;
        try {
            sheep = (Sheep)super.clone();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return sheep;
    }
    public Sheep(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

新添的Cow类

public class Cow {
    private String name;
    private int age;
    public Cow(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Cow{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

客户端调用克隆

public class Client {
    public static void main(String[] args) {
        Sheep sheepDolly=new Sheep("Dolly",2);
        sheepDolly.friend=new Cow("Tom",1); //并实例化朋友
        Sheep sheep1 = (Sheep)sheepDolly.clone();
        Sheep sheep2 = (Sheep)sheepDolly.clone();
        Sheep sheep3 = (Sheep)sheepDolly.clone();
        //....
        System.out.println("sheep1:"+sheep1+",hashCode:" + sheep1.hashCode());
        System.out.println("sheep1.friend:"+sheep1.friend+",hashCode:" + sheep1.friend.hashCode()+'\n');
        System.out.println("sheep2:"+sheep2+",hashCode:" + sheep2.hashCode());
        System.out.println("sheep2.friend:"+sheep2.friend+",hashCode:" + sheep2.friend.hashCode()+'\n');
        System.out.println("sheep3:"+sheep3+",hashCode:" + sheep3.hashCode());
        System.out.println("sheep3.friend:"+sheep3.friend+",hashCode:" + sheep3.friend.hashCode()+'\n');
        //...
    }
}

运行结果

java设计模式--原型模式详解

通过运行结果发现,浅拷贝通过Object的clone()成功克隆实例化了三个新对象,但是并没有克隆实例化对象中的引用属性,也就是没有克隆friend对象(禁止套娃 ),三个新克隆对象的friend还是指向原克隆前的friend,即同一个对象。

这样的话,他们四个的friend是引用同一个,若一个对象修改了friend属性,势必会影响其他三个对象的该成员变量值。

小结:

  • 浅拷贝是使用默认的 clone()方法来实现
  • 基本数据类型的成员变量,浅拷贝会直接进行值传递(复制属性值给新对象)。
  • 引用数据类型的成员变量,浅拷贝会进行引用传递(复制引用值(内存地址)给新对象)。

深拷贝

方法一:

机灵的人儿看出,再clone一遍cow不就好了,但是手动递归下去不推荐。

1.Cow类也实现Cloneable接口

public class Cow implements Cloneable{
    private String name;
    private int age;
    public Cow(String name, int age) {
        this.name = name;
        this.age = age;
    }
    //无引用类型,直接clone即可
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone(); //直接抛出了,没用try-catch
    }
    @Override
    public String toString() {
        return "Cow{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Sheep类的clone再添加调用cow的clone

public class Sheep implements Cloneable{
    private String name;
    private int age;
    public Cow friend;//新朋友Cow对象,其余不变
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        //完成对基本数据类型(属性)和String的克隆
        deep = super.clone();
        //对引用类型的属性,进行再次clone
        Sheep sheep = (Sheep)deep;
        sheep.friend  = (Cow)friend.clone();
        return sheep;
    }
    public Sheep(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

客户端调用

public class Client {
    public static void main(String[] args) throws CloneNotSupportedException {
        Sheep sheepDolly=new Sheep("Dolly",2);
        sheepDolly.friend=new Cow("Tom",1); //并实例化朋友
        Sheep sheep1 = (Sheep)sheepDolly.clone();
        Sheep sheep2 = (Sheep)sheepDolly.clone();
        Sheep sheep3 = (Sheep)sheepDolly.clone();
        //....
        System.out.println("sheep1:"+sheep1+",hashCode:" + sheep1.hashCode());
        System.out.println("sheep1.friend:"+sheep1.friend+",hashCode:" + sheep1.friend.hashCode()+'\n');
        System.out.println("sheep2:"+sheep2+",hashCode:" + sheep2.hashCode());
        System.out.println("sheep2.friend:"+sheep2.friend+",hashCode:" + sheep2.friend.hashCode()+'\n');
        System.out.println("sheep3:"+sheep3+",hashCode:" + sheep3.hashCode());
        System.out.println("sheep3.friend:"+sheep3.friend+",hashCode:" + sheep3.friend.hashCode()+'\n');
        //...
    }
}

运行结果

java设计模式--原型模式详解

方法二:

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

1.Cow类实现序列化接口,不必实现Cloneable接口了

public class Cow implements Serializable {
    private String name;
    private int age;
    public Cow(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Cow{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

2.在Sheep类实现序列化接口

public class Sheep implements Serializable { //实现序列化接口
    private String name;
    private int age;
    public Cow friend;

    public Sheep(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    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);
            Sheep sheep = (Sheep) ois.readObject();
            return sheep;
        } 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());
            }
        }
    }
}

3.客户端调用

public class Client {
    public static void main(String[] args) throws CloneNotSupportedException {
        Sheep sheepDolly=new Sheep("Dolly",2);
        sheepDolly.friend=new Cow("Tom",1); //并实例化朋友
        Sheep sheep1 = (Sheep)sheepDolly.deepClone();
        Sheep sheep2 = (Sheep)sheepDolly.deepClone();
        Sheep sheep3 = (Sheep)sheepDolly.deepClone();
        //....
        System.out.println("sheep1:"+sheep1+",hashCode:" + sheep1.hashCode());
        System.out.println("sheep1.friend:"+sheep1.friend+",hashCode:" + sheep1.friend.hashCode()+'\n');
        System.out.println("sheep2:"+sheep2+",hashCode:" + sheep2.hashCode());
        System.out.println("sheep2.friend:"+sheep2.friend+",hashCode:" + sheep2.friend.hashCode()+'\n');
        System.out.println("sheep3:"+sheep3+",hashCode:" + sheep3.hashCode());
        System.out.println("sheep3.friend:"+sheep3.friend+",hashCode:" + sheep3.friend.hashCode()+'\n');
        //...
    }
}

运行结果

java设计模式--原型模式详解

原型模式总结:

  • 创建新的对象比较复杂时,可以利用原型模式简化对象的创建过程,同时也能够提高效率
  • 可以不用重新初始化对象,动态地获得对象运行时的状态。
  • 如果原始对象发生变化(增加或者减少属性),其它克隆对象的也会发生相应的变化,无需修改代码
  • 若成员变量无引用类型,浅拷贝clone即可;若引用类型的成员变量很少,可考虑递归实现clone,否则推荐序列化。

总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注三水点靠木的更多内容!

Java/Android 相关文章推荐
springBoot基于webSocket实现扫码登录
Jun 22 Java/Android
Maven学习----Maven安装与环境变量配置教程
Jun 29 Java/Android
Java 语言中Object 类和System 类详解
Jul 07 Java/Android
springboot集成springCloud中gateway时启动报错的解决
Jul 16 Java/Android
浅谈spring boot使用thymeleaf版本的问题
Aug 04 Java/Android
解析探秘fescar分布式事务实现原理
Feb 28 Java/Android
Android基于Fresco实现圆角和圆形图片
Apr 01 Java/Android
Android开发实现极为简单的QQ登录页面
Apr 24 Java/Android
JAVA 线程池(池化技术)的实现原理
Apr 28 Java/Android
Android studio 简单计算器的编写
May 20 Java/Android
java获取一个文本文件的编码(格式)信息
Sep 23 Java/Android
SpringBoot快速入门详解
java设计模式--三种工厂模式详解
gateway与spring-boot-starter-web冲突问题的解决
Jul 16 #Java/Android
springboot集成springCloud中gateway时启动报错的解决
Jul 16 #Java/Android
JavaWeb 入门篇(3)ServletContext 详解 具体应用
JavaWeb 入门:Hello Servlet
JavaWeb 入门篇:创建Web项目,Idea配置tomcat
You might like
php表单提交问题的解决方法
2011/04/12 PHP
PHP处理大量表单字段的便捷方法
2015/02/07 PHP
php读取csv文件并输出的方法
2015/03/14 PHP
php通过前序遍历树实现无需递归的无限极分类
2015/07/10 PHP
PHP登录验证功能示例【用户名、密码、验证码、数据库、已登陆验证、自动登录和注销登录等】
2019/02/25 PHP
分享几个超级震憾的图片特效
2012/01/08 Javascript
Javascript模块化编程(一)AMD规范(规范使用模块)
2013/01/17 Javascript
在javaScript中关于submit和button的区别介绍
2013/10/20 Javascript
js加载读取内容及显示与隐藏div示例
2014/02/13 Javascript
js动态拼接正则表达式的两种方法
2014/03/04 Javascript
原生js实现复制对象、扩展对象 类似jquery中的extend()方法
2014/08/30 Javascript
JS实现判断碰撞的方法
2015/02/11 Javascript
详解javascript new的运行机制
2016/01/26 Javascript
jquery.flot.js简单绘制折线图用法示例
2017/03/13 Javascript
利用vue.js插入dom节点的方法
2017/03/15 Javascript
angularjs实现猜大小功能
2017/10/23 Javascript
jquery.picsign图片标注组件实例详解
2018/02/02 jQuery
jquery的 filter()方法使用教程
2018/03/22 jQuery
vue实现简单的MVVM框架
2018/08/05 Javascript
vue项目持久化存储数据的实现代码
2018/10/01 Javascript
基于Vue中使用节流Lodash throttle详解
2019/10/30 Javascript
Vue 中 template 有且只能一个 root的原因解析(源码分析)
2020/04/11 Javascript
[02:07]2017国际邀请赛中国区预选赛直邀战队前瞻
2017/06/23 DOTA
python 参数列表中的self 显式不等于冗余
2008/12/01 Python
详解Python中内置的NotImplemented类型的用法
2015/03/31 Python
Python 获得13位unix时间戳的方法
2017/10/20 Python
python 对给定可迭代集合统计出现频率,并排序的方法
2018/10/18 Python
Python微信操控itchat的方法
2019/05/31 Python
基于Python的Post请求数据爬取的方法详解
2019/06/14 Python
python networkx 根据图的权重画图实现
2019/07/10 Python
python 基于opencv 绘制图像轮廓
2020/12/11 Python
ManoMano英国:欧洲第一家专注于DIY和园艺市场的电商平台
2020/03/12 全球购物
小学生期末评语大全
2014/04/21 职场文书
教师师德演讲稿
2014/05/06 职场文书
使用这 6个Vue加载动画库来减少我们网站的跳出率
2021/05/18 Vue.js
mysql left join快速转inner join的过程
2021/06/30 MySQL