java中的原型模式是什么

发布时间:2021-07-20 10:20:17 作者:chen
来源:亿速云 阅读:171

本篇内容主要讲解“java中的原型模式是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java中的原型模式是什么”吧!

目录

引例

问题:

现在有一只羊(包含属性:名字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中的原型模式是什么

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

浅拷贝

在原先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一遍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中的原型模式是什么

原型模式总结:

到此,相信大家对“java中的原型模式是什么”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. 在C++和Java中如何实现原型模式
  2. Prototype原型模式的作用是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:虚拟机Linux系统忘记密码修改root或其他用户密码怎么办

下一篇:怎么修改gazebo物理参数

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》