|
介绍
动态地给一个对象添加一些额外的职责。就扩展功能而言,它比生成子类方式更为灵活。
示例
有一个Message实体类,某个对象对它的操作有Insert()和Get()方法,现在扩展这个对象的功能。
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Pattern.Decorator
- {
- /**//// <summary>
- /// Message实体类
- /// </summary>
- public class MessageModel
- {
- /**//// <summary>
- /// 构造函数
- /// </summary>
- /// <param name="msg">Message内容</param>
- /// <param name="pt">Message发布时间</param>
- public MessageModel(string msg, DateTime pt)
- {
- this._message = msg;
- this._publishTime = pt;
- }
- private string _message;
- /**//// <summary>
- /// Message内容
- /// </summary>
- public string Message
- {
- get { return _message; }
- set { _message = value; }
- }
- private DateTime _publishTime;
- /**//// <summary>
- /// Message发布时间
- /// </summary>
- public DateTime PublishTime
- {
- get { return _publishTime; }
- set { _publishTime = value; }
- }
- }
- }
- AbstractMessage
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Pattern.Decorator
- {
- /**//// <summary>
- /// 操作Message的抽象构件(Component)
- /// </summary>
- public abstract class AbstractMessage
- {
- /**//// <summary>
- /// 获取Message
- /// </summary>
- /// <returns></returns>
- public abstract List<MessageModel> Get();
- /**//// <summary>
- /// 插入Message
- /// </summary>
- /// <param name="mm">Message实体对象</param>
- /// <returns></returns>
- public abstract bool Insert(MessageModel mm);
- }
- }
复制代码 |
|