Creational Patterns Part 5/5: Prototype Pattern

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值