Java设计模式————原型模式

1 原型模式

1.1 基本介绍

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

1.2 例子

  • 对象(引入了Lombok)
@Data
public class Person implements Cloneable {
    private String name;
    private int age;
    private String gender;

	//克隆对象方法
    @Override
    protected Person clone() {

        Person person = null;
        try {
            person = (Person) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return person;
    }
}

  • 测试
public class test {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("zj");
        person.setAge(20);
        person.setGender("女");
        System.out.println(person);

        Person clone = person.clone();
        System.out.println(clone);

        System.out.println(person == clone);


    }
}

  • 结果
    在这里插入图片描述

2 浅拷贝

2.1 基本介绍

(1)对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复能一份给新的对象。
(2)对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组、某个类的对象等,那么浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制一-份给新的对象。因为实际上两个对象的该成员变量都指向同一个实例。在这种情况下,在一个对象中修改该成员变量会影响到另一个对象的该成员变量值
(3)浅拷贝是使用默认的clone()方法来实现

  • 前面的例子即是浅拷贝

2.2 例子

  • 对前面Person类进行修改
@Data
public class Person implements Cloneable {
    private String name;
    private int age;
    private String gender;
    private Person friend;

    @Override
    protected Person clone() {

        Person person = null;
        try {
            person = (Person) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return person;
    }
}

  • 启动类
public class test {
    public static void main(String[] args) {
        Person p = new Person();
        p.setName("fmx");
        p.setAge(22);
        p.setGender("男");
        Person person = new Person();
        person.setName("zj");
        person.setAge(20);
        person.setGender("女");
        person.setFriend(p);

        Person clone = person.clone();

        System.out.println(person + "=======" + person.getFriend().hashCode());
        System.out.println(clone + "=======" + clone.getFriend().hashCode());
        System.out.println(person == clone);


    }
}

  • 结果
    在这里插入图片描述
    输出结果中,克隆对象与原对象中的引用类型属性指向同一地址。

3 深拷贝

3.1 基本介绍

(1)复制对象的所有基本数据类型的成员变量值
(2)为所有引用数据类型的成员变量申请存储空间,并复制每个引用数据类型成员变量所引用的对象,直到该对象可达的所有对象。也就是说,对象进行深拷贝要对整个对象进行拷贝
(3)深拷贝实现方式1:重写clone方法来实现深拷贝
(4)深拷贝实现方式2:通过对象序列化实现深拷贝

3.2 例子

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

@Data
public class Friend implements Serializable, Cloneable {
    private String name;
    private String gender;
    private String phoneNum;

    @Override
    protected Friend clone() {
        Friend friend = null;
        try {
            friend = (Friend) super.clone();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return friend;
    }
}

@Data
public class Person implements Serializable, Cloneable {
    private String name;
    private int age;
    private String gender;
    private Friend friend;

    @Override
    protected Person clone() {

        Person person = null;
        try {
            person = (Person) super.clone();
            Friend clone = friend.clone();
            person.setFriend(clone);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return person;
    }
}

  • 启动类
public class test {
    public static void main(String[] args) {
        Friend friend = new Friend();
        friend.setName("zj");
        friend.setGender("女");
        friend.setPhoneNum("18888888888");

        Person p1 = new Person();
        p1.setName("fmx");
        p1.setAge(22);
        p1.setGender("男");
        p1.setFriend(friend);

        Person p2 = p1.clone();
        System.out.println("p1=p2?: " + (p1 == p2));
        System.out.println("p1:" + p1 + "----------- p1.hashCode:" + p1.hashCode());
        System.out.println("p2:" + p2 + "----------- p2.hashCode:" + p2.hashCode());

        Friend f1 = p1.getFriend();
        Friend f2 = p2.getFriend();
        System.out.println("f1=f2?: " + (f1 == f2));
        System.out.println("f1:" + f1 + "----------- f1.hashCode:" + f1.hashCode());
        System.out.println("f2:" + f2 + "----------- f2.hashCode:" + f2.hashCode());

    }
}

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

@Data
public class Friend implements Serializable, Cloneable {
    private String name;
    private String gender;
    private String phoneNum;

    @Override
    protected Friend clone() {
        Friend friend = null;
        try {
            friend = (Friend) super.clone();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return friend;
    }
}

@Data
public class Person implements Serializable, Cloneable {
    private String name;
    private int age;
    private String gender;
    private Friend friend;

    public Object personClone() {
        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);
            Person person = (Person) ois.readObject();
            return person;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

@Data
public class Person implements Serializable, Cloneable {
    private String name;
    private int age;
    private String gender;
    private Friend friend;

    public Person personClone() {
        Person person = null;
        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);
            person = (Person) ois.readObject();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return person;
    }
}

  • 启动类
public class test {
    public static void main(String[] args) {
        Friend friend = new Friend();
        friend.setName("zj");
        friend.setGender("女");
        friend.setPhoneNum("18888888888");

        Person p1 = new Person();
        p1.setName("fmx");
        p1.setAge(22);
        p1.setGender("男");
        p1.setFriend(friend);

        Person p2 = p1.personClone();
        System.out.println("p1=p2?: " + (p1 == p2));
        System.out.println("p1:" + p1 + "----------- p1.hashCode:" + p1.hashCode());
        System.out.println("p2:" + p2 + "----------- p2.hashCode:" + p2.hashCode());

        Friend f1 = p1.getFriend();
        Friend f2 = p2.getFriend();
        System.out.println("f1=f2?: " + (f1 == f2));
        System.out.println("f1:" + f1 + "----------- f1.hashCode:" + f1.hashCode());
        System.out.println("f2:" + f2 + "----------- f2.hashCode:" + f2.hashCode());

    }
}

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

(1)创建新的对象比较复杂时,可以利用原型模式简化对象的创建过程,同时也能够提高效率
(2)不用重新初始化对象,而是动态地获得对象运行时的状态
(3)如果原始对象发生变化(增加或者减少属性):其它克隆对象的也会发生相应的编号,无需修改代码
(4)在实现深克隆的时候可能需要比较复杂的代码
(5)缺点:需要为每一个类配备一个克隆方法,这对全新的类来说不是很难,但对已有的类进行改造时,需要修改其源代码,违背了ocp原则

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值