第05章 创建型-原型模式

本文内容来源于网络收集

作者:冰河
来源:冰河技术公众号

  • 本章难度:★★☆☆☆
  • 本章重点:用最简短的篇幅介绍原型模式最核心的知识,理解原型模式的设计精髓,并能够灵活运用到实际项目中,编写可维护的代码。

一、概述

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

二、适用性

1.当一个系统应该独立于它的产品创建、构成和表示时。

2.当要实例化的类是在运行时刻指定时,例如,通过动态装载。

3.为了避免创建一个与产品类层次平行的工厂类层次时。

4.当一个类的实例只能有几个不同状态组合中的一种时。

建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。

三、参与者

1.Prototype 声明一个克隆自身的接口。

2.ConcretePrototype 实现一个克隆自身的操作。

3.Client 让一个原型克隆自身从而创建一个新的对象。


四、示例

Prototype

 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
/**
 * @author binghe(微信 : hacker_binghe)
 * @version 1.0.0
 * @description 原型类,实现Cloneable接口
 * @github https://github.com/binghe001
 * @copyright 公众号: 冰河技术
 */
public class Prototype implements Cloneable{

    private String name;
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return this.name;
    }
    public Object clone(){
        try {
            return super.clone();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

ConcretePrototype

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
/**
 * @author binghe(微信 : hacker_binghe)
 * @version 1.0.0
 * @description 原型类的子类,用于构建原型
 * @github https://github.com/binghe001
 * @copyright 公众号: 冰河技术
 */
public class ConcretePrototype extends Prototype {

    public ConcretePrototype(String name) {
        setName(name);
    }
}

Client

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
/**
 * @author binghe(微信 : hacker_binghe)
 * @version 1.0.0
 * @description  测试类
 * @github https://github.com/binghe001
 * @copyright 公众号: 冰河技术
 */
public class Test {

    public static void main(String[] args) {
        Prototype pro = new ConcretePrototype("prototype");
        Prototype pro2 = (Prototype)pro.clone();
        System.out.println(pro.getName());
        System.out.println(pro2.getName());
    }
}

result

1
2
prototype
prototype