程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> 設計模式(C#) - 建造者模式(Builder Pattern)

設計模式(C#) - 建造者模式(Builder Pattern)

編輯:關於C#

返回“設計模式(C#)系列文章索引”

介紹

將一個復雜對象的構建與它的表示分離,使得同樣的構建過程可以創建不同的表示。

示例

用同樣的構建過程創建Sql和Xml的Insert()方法和Get()方法。

MessageModel

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.Builder
{
  /**//// <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; }
    }
  }
}

SqlMessage

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.Builder
{
  /**//// <summary>
  /// Sql方式操作Message
  /// </summary>
  public class SqlMessage
  {
    /**//// <summary>
    /// 獲取Message
    /// </summary>
    /// <returns></returns>
    public List<MessageModel> Get()
    {
      List<MessageModel> l = new List<MessageModel>();
      l.Add(new MessageModel("SQL方式獲取Message", DateTime.Now));

      return l;
    }

    /**//// <summary>
    /// 插入Message
    /// </summary>
    /// <param name="mm">Message實體對象</param>
    /// <returns></returns>
    public bool Insert(MessageModel mm)
    {
      // 代碼略
      return true;
    }
  }
}

XmlMessage

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.Builder
{
  /**//// <summary>
  /// Xml方式操作Message
  /// </summary>
  public class XmlMessage
  {
    /**//// <summary>
    /// 獲取Message
    /// </summary>
    /// <returns></returns>
    public List<MessageModel> Get()
    {
      List<MessageModel> l = new List<MessageModel>();
      l.Add(new MessageModel("XML方式獲取Message", DateTime.Now));

      return l;
    }

    /**//// <summary>
    /// 插入Message
    /// </summary>
    /// <param name="mm">Message實體對象</param>
    /// <returns></returns>
    public bool Insert(MessageModel mm)
    {
      // 代碼略
      return true;
    }
  }
}

Operation

using System;
using System.Collections.Generic;
using System.Text;

using System.Reflection;

namespace Pattern.Builder
{
  /**//// <summary>
  /// 操作(Product)
  /// </summary>
  public class Operation
  {
    private string _type;
    private Dictionary<string, string> _dictionary;

    /**//// <summary>
    /// 構造函數
    /// </summary>
    /// <param name="type">產品類型</param>
    public Operation(string type)
    {
      _dictionary = new Dictionary<string, string>();
      this._type = type;
    }

    /**//// <summary>
    /// 索引器
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public string this[string key]
    {
      get { return _dictionary[key]; }
      set { _dictionary[key] = value; }
    }

    /**//// <summary>
    /// 獲得結果
    /// </summary>
    /// <returns></returns>
    public string GetResult()
    {
      Assembly assembly = Assembly.Load("Pattern.Builder");

      MethodInfo methodGet = assembly.GetType("Pattern.Builder." + _dictionary["get"].Split('|')[0]).GetMethod(_dictionary["get"].Split('|')[1]);
      object objGet = methodGet.Invoke(assembly.CreateInstance("Pattern.Builder." + _dictionary["get"].Split('|')[0]), null);
      List<MessageModel> m = (List<MessageModel>)objGet;

      MethodInfo methodInsert = assembly.GetType("Pattern.Builder." + _dictionary["insert"].Split('|')[0]).GetMethod(_dictionary["insert"].Split('|')[1]);
      object objInsert = methodInsert.Invoke(assembly.CreateInstance("Pattern.Builder." + _dictionary["insert"].Split('|')[0]), new object[] { new MessageModel(_dictionary["insert"].Split('|')[2], Convert.ToDateTime(_dictionary["insert"].Split('|')[3])) });
      bool b = (bool)objInsert;

      return "類型為" + this._type + "的執行結果:<br />" + b.ToString() + "<br />" + m[0].Message + " " + m[0].PublishTime.ToString() + "<br />";
    }
  }
}

AbstractMessageBuilder

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.Builder
{
  /**//// <summary>
  /// 抽象Message建造者(Builder)
  /// </summary>
  public abstract class AbstractMessageBuilder
  {
    /**//// <summary>
    /// 構造函數
    /// </summary>
    /// <param name="type">產品類型</param>
    public AbstractMessageBuilder(string type)
    {
      this._operation = new Operation(type);
    }

    /**//// <summary>
    /// 操作(Product)
    /// </summary>
    protected Operation _operation;
    /**//// <summary>
    /// 操作(Product)
    /// </summary>
    public Operation Operation
    {
      get { return _operation; }
      set { _operation = value; }
    }

    /**//// <summary>
    /// 建造插入方法
    /// </summary>
    /// <param name="mm"></param>
    abstract public void BuilderInsert(MessageModel mm);

    /**//// <summary>
    /// 建造獲取方法
    /// </summary>
    abstract public void BuilderGet();
  }
}

SqlMessageBuilder

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.Builder
{
  /**//// <summary>
  /// SqlMessage建造者(ConcreteBuilder)
  /// </summary>
  public class SqlMessageBuilder : AbstractMessageBuilder
  {
    /**//// <summary>
    /// 構造函數
    /// </summary>
    public SqlMessageBuilder()
      : base("sql")
    {
    }

    /**//// <summary>
    /// 建造Sql插入方法
    /// </summary>
    /// <param name="mm">Message實體對象</param>
    public override void BuilderInsert(MessageModel mm)
    {
      base._operation["insert"] = "SqlMessage|Insert|" + mm.Message + "|" + mm.PublishTime.ToString() + "";
    }

    /**//// <summary>
    /// 建造Sql獲取方法
    /// </summary>
    public override void BuilderGet()
    {
      base._operation["get"] = "SqlMessage|Get";
    }
  }
}

XmlMessageBuilder

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.Builder
{
  /**//// <summary>
  /// XmlMessage建造者(ConcreteBuilder)
  /// </summary>
  public class XmlMessageBuilder : AbstractMessageBuilder
  {
    /**//// <summary>
    /// 構造函數
    /// </summary>
    public XmlMessageBuilder()
      : base("xml")
    {
    }

    /**//// <summary>
    /// 建造Xml插入方法
    /// </summary>
    /// <param name="mm">Message實體對象</param>
    public override void BuilderInsert(MessageModel mm)
    {
      base._operation["insert"] = "XmlMessage|Insert|"+mm.Message+"|"+mm.PublishTime.ToString()+"";
    }

    /**//// <summary>
    /// 建造Xml獲取方法
    /// </summary>
    public override void BuilderGet()
    {
      base._operation["get"] = "XmlMessage|Get";
    }
  }
}

Message

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.Builder
{
  /**//// <summary>
  /// 指導者(Director)
  /// </summary>
  public class Message
  {
    /**//// <summary>
    /// 調用具體建造者角色以創建產品對象
    /// </summary>
    /// <param name="messageBuilder">AbstractMessageBuilder</param>
    /// <param name="mm">Message實體對象</param>
    public void Construct(AbstractMessageBuilder messageBuilder, MessageModel mm)
    {
      messageBuilder.BuilderInsert(mm);
      messageBuilder.BuilderGet();
    }
  }
}

client

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Pattern.Builder;

public partial class Builder : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    Message m = new Message();

    AbstractMessageBuilder amb = new SqlMessageBuilder();
    m.Construct(amb, new MessageModel("插入", DateTime.Now));

    Response.Write(amb.Operation.GetResult());

    amb = new XmlMessageBuilder();
    m.Construct(amb, new MessageModel("插入", DateTime.Now));

    Response.Write(amb.Operation.GetResult());
  }
}

運行結果

類型為sql的執行結果:

True

SQL方式獲取Message 2007-5-5 20:53:28

類型為xml的執行結果:

True

XML方式獲取Message 2007-5-5 20:53:28

參考

http://www.dofactory.com/Patterns/PatternBuilder.aspx

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved