PROTOTYPE(原型模式)

来源:互联网 发布:dior fix it color 编辑:程序博客网 时间:2024/06/08 01:21
1. 意图

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

2. 适用性
当一个系统应该独立于它的产品创建、构成和表示时,要使用 Prototype模式;以及
• 当要实例化的类是在运行时刻指定时,例如,通过动态装载;或者
• 为了避免创建一个与产品类层次平行的工厂类层次时;或者
• 当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们
可能比每次用合适的状态手工实例化该类更方便一些。

3. 结 构


4. 参与者
• Prototype
— 声明一个克隆自身的接口。
• ConcretePrototype
— 实现一个克隆自身的操作。
• Client
— 让一个原型克隆自身从而创建一个新的对象。

5.代码结构


6.代码实现

Prototype.cs

using UnityEngine;using System.Collections;public abstract class Prototype {    private string name;    public string Name {        get { return name;}        set { name = value;}    }    public abstract Prototype Clone();}

ConcretePrototype.cs

using UnityEngine;using System.Collections;using System;public class ConcretePrototype : Prototype{    public override Prototype Clone()    {        ConcretePrototype obj = new ConcretePrototype();        obj.Name = this.Name;        return obj;    }}
Client.cs

using UnityEngine;using System.Collections;public class Client : MonoBehaviour {// Use this for initializationvoid Start () {        ConcretePrototype a = new ConcretePrototype();        a.Name = "张三";        ConcretePrototype b = (ConcretePrototype)a.Clone();        b.Name = "李四";    }}




0 0
原创粉丝点击