关闭

Creational Patterns Part 5/5: Prototype Pattern

标签: 原型模式创造型模式设计模式
154人阅读 评论(0) 收藏 举报
分类:

Creational Patterns Part 5/5: Prototype Pattern

目录


Definition

Prototype Pattern会根据指定的Prototype(原型)去制造(Make)而不是创建(New)一个新的对象。
要知道每次new对象是很耗时的操作。Prototype Pattern会在克隆时间点制造出一个一模一样的对象(也就是两者在那一瞬间的state一样)出来,除此之外,对象在clone出来之后与prototype并无联系。

何时使用?希望避免new对象带来的损耗时或者是创建的对象都很相似时(比如一堆围棋)。

使用频率:Frequncey of use Medium


UML Class Diagram

Prototype Pattern


Implementation

Prototype Pattern相对来说还是比较简单的,下面以拷贝一个Student类为例。
注意到student和student2仅在clone时状态完全一样,但是此后两者便是独立没有联系的(前提是深拷贝)。

// PrototypeDemo.java
package designpatterns.creationalpatterns.prototype;

public class PrototypeDemo {
    public static void main(String[] args) {
        Cellphone cp = new Cellphone("NOKIA");
        Person student = new Student("Stephen", cp);
        Person student2 = student.Clone();
        System.out.println(student);
        System.out.println(student2);
        System.out.println("========================");
        student.setCellphone(new Cellphone("iPhone"));
        System.out.println(student);
        System.out.println(student2);
    }
}

abstract class Person implements Cloneable {
    protected String name;
    protected Cellphone cellphone;

    public Person(String name, Cellphone cp) {
        this.name = name;
        this.cellphone = cp;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Cellphone getCellphone() {
        return cellphone;
    }

    public void setCellphone(Cellphone cellphone) {
        this.cellphone = cellphone;
    }

    public abstract Person Clone();

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + ", " + name + ", " + cellphone;
    }
}

class Student extends Person {

    public Student(String name, Cellphone cp) {
        super(name, cp);
    }

    @Override
    public Person Clone() {
        Person person = null;       
        try {
            person = (Person) super.clone();
        } catch (Exception e) {
            e.printStackTrace();
        }       
        return person;
    }


}

class Cellphone {
    private String brand;

    public Cellphone() {}

    public Cellphone(String brand) {
        this.brand = brand;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    @Override
    public String toString() {
        return brand;
    }
}

// output
Student, Stephen, NOKIA
Student, Stephen, NOKIA
========================
Student, Stephen, iPhone
Student, Stephen, NOKIA
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:21015次
    • 积分:968
    • 等级:
    • 排名:千里之外
    • 原创:79篇
    • 转载:0篇
    • 译文:1篇
    • 评论:0条