Post

设计模式系列-原型模式

原型模式的类做了这样一个事情:该类可以创建当前对象的一个克隆,从而规避某些情况下直接创建对象代价比较大的问题。(某些情况下,通过new 去创建一个对象,需要非常繁琐的步骤,如:数据准备和检查访问权限等。使用原型模式可以简化这些操作。) 例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。

在java中, 实现原型模式的步骤:

第一步: 原型类Prototype实现Cloneable接口, 第二步: 重写Object的clone()方法,对于不同属性,选择深拷贝or浅拷贝 第三步: 在目标类也就是PrototypeTest类型调用Prototype类的clone方法, 实现对象的复制.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class Prototype implements Cloneable{

    private String name;
    private int age;
    private String sex;
    private ArrayList<String> hobbies;

    public Prototype(String name, int age, String sex, ArrayList<String> hobbies) {
        this.name = name;
        this.age = age;
        this. sex = sex;
        this.hobbies = hobbies;
    }

    /**
     * 重写object的clone()方法, 并将其作用域设置为public
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    public Prototype clone() throws CloneNotSupportedException {
        Prototype clone = (Prototype)super.clone();
        System.out.println("浅拷贝:" + (clone.hobbies == this.hobbies));
        clone.hobbies = (ArrayList<String>) (this.hobbies).clone();
        System.out.println("深拷贝:" + (clone.hobbies == this.hobbies));
        return clone;
    }

    @Override
    public String toString() {
        return "Prototype{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}

public class PrototypeTest {

    public static void main(String[] args) throws CloneNotSupportedException {
        ArrayList hobbies = new ArrayList();
        hobbies.add("篮球");
        hobbies.add("排期");
        Prototype prototype = new Prototype("张三", 8, "男", hobbies);
        Prototype cloneObject = (Prototype)prototype.clone();

        System.out.println("比较克隆前后的对象:"+(prototype == cloneObject));
        System.out.println("比较克隆前后的List<String>属性:" + (prototype.getHobbies() == cloneObject.getHobbies()));
    }
}
This post is licensed under CC BY 4.0 by the author.