Java设计模式:原型模式

300 阅读6分钟

克隆羊问题

       现在有一只羊tom,姓名为: tom, 年龄为:1,颜色为:白色,请编写程序创建和tom羊 属性完全相同的10只羊。

传统方式解决克隆羊问题

代码演示:

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 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;
    }
    @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("多莉", 5, "白色");
        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());
//        ............    }
}

传统的方式的优缺点

1) 优点是比较好理解,简单易操作。
2) 在创建新的对象时,总是需要重新获取原始对象的属性,如果创建的对象比较复杂
时,效率较低
3) 总是需要重新初始化对象,而不是动态地获得对象运行时的状态, 不够灵活
4) 改进的思路分析
**思路**:Java中Object类是所有类的根类,Object类提供了一个clone()方法,该方法可以
将一个Java对象复制一份,但是需要实现clone的Java类必须要实现一个接口Cloneable,
该接口表示该类能够复制且具有复制的能力 => 原型模式

原型模式

基本介绍

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

原型模式解决克隆羊问题

代码演示:

Sheep方法不变,增加重写clone方法

//    克隆该实例,使用默认的clone方法来完成
    @Override
    protected Object clone(){
        Sheep sheep = null;
        try {
            sheep = (Sheep) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return sheep;
    }

public class Client {
    public static void main(String[] args) {
        Sheep sheep = new Sheep("多莉", 5, "白色");
//        克隆
        Sheep sheep1 = (Sheep) sheep.clone();
        Sheep sheep2 = (Sheep) sheep.clone();
        Sheep sheep3 = (Sheep) sheep.clone();
        Sheep sheep4 = (Sheep) sheep.clone();
//        .............
    }
}

浅拷贝和深拷贝

浅拷贝的介绍

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

深拷贝基本介绍

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

深拷贝实现方式1

代码演示:

public class Student implements Cloneable {//简单的定义一个student类,这里省略了get、set方法
    private String name;
    private int age;
    private  String gender;

    public Student() {
    }    
public Student(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
//    因为该类的属性都是基础数据类型,因此这里使用默认的clone完成即可
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class StudentResult implements Cloneable {//定义一个StudentResult类来引用Student,重写clone来完成深拷贝
    private Student student;
    private double result;
    public StudentResult() {
    }
    public StudentResult(Student student,double result) {
        this.result = result;
        this.student = student;
    }
    public Student getStudent() {
        return student;
    }
    public void setStudent(Student student) {
        this.student = student;
    }
    public double getResult() {
        return result;
    }
    public void setResult(double result) {
        this.result = result;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object studentClone = null;

//        这里完成对基本类型(属性)的string的克隆
        studentClone = super.clone();

//        对引用类型的属性,进行单独处理
        StudentResult studentResult = (StudentResult)studentClone;
        studentResult.student = (Student)student.clone();
        return studentResult;
    }
}

public class Client {//客户端,这里来测试clone拷贝的hashCode是否相同,来检验是否是深拷贝
    public static void main(String[] args) {
        Student student = new Student("张三", 21, "男");
        StudentResult studentResult = new StudentResult(student, 70);
        StudentResult studentResult1 = null;
        try {
            studentResult1 = (StudentResult)studentResult.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        System.out.println("studentResult.getResult = " + studentResult.getResult() +"studentResult.getStudent" + studentResult.getStudent().hashCode());
        System.out.println("studentResult1.getResult = " + studentResult1.getResult() +"studentResult1.getStudent" + studentResult1.getStudent().hashCode());
    }
}

测试结果:hashCode不一样,是深拷贝
studentResult.getResult = 70.0studentResult.getStudent793589513
studentResult1.getResult = 70.0studentResult1.getStudent1323165413

深拷贝实现方式2(推荐)

代码演示:

使用Serializable接口将Student和StudentResult 序列化

public class Student implements Serializable {//对象序列化,这里省略了get、set、toString
    public static final long serialVersionUID = 456465456L;
    private String name;
    private int age;
    private  String gender;
    public Student() {
    }
    public Student(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
}

public class StudentResult implements Serializable {//对象序列化,这里省略了get、set、toString
    public static final long serialVersionUID = 4523424456L;
    private Student student;
    private double result;
    public StudentResult() {
    }
    public StudentResult(Student student, double result) {
        this.result = result;
        this.student = student;
    }
}

public class Client {
    public static void main(String[] args) {
        Student student = new Student("张三", 21, "男");
        StudentResult studentResult = new StudentResult(student, 70);

//        序列化
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
            oos.writeObject(studentResult);
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (oos != null)
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

//        反序列化
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.dat"));
            StudentResult str = (StudentResult)ois.readObject();
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

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

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

注:本文章大量借鉴尚硅谷公开视频资料的内容,如有不妥之处立即删除。对文章有不懂的地方,可以直接去尚硅谷的官方网站学习。