官术网_书友最值得收藏!

1.8 一個服務示例

根據前述的所有原則,我們一起來看一個實際生活中的示例。代碼清單1.13是DialogService的代碼。這個服務用于在一個對話框中顯示有用的消息。

代碼清單1.13 服務實現示例


/// <summary>
/// Interface for a service that displays messages to the user.
/// </summary>
public interface IDialogService
{
  /// <summary>
  /// Show the given message to the user in a dialog
  /// with just an OK button.
  /// </summary>
  void Show(string pUserMessage);
  /// <summary>
  /// Show a message to the user with the specified
  /// window caption and buttons.
  /// </summary>
  DialogResult Show(string pUserMessage, string pCaption,
    MessageBoxButtons pMessageBoxButtons);
}
/// <summary>
/// The dialog service will show a message to the user
/// and accept an appropriate response as requested
/// by the caller.
/// </summary>
public class DialogService : IDialogService
{
  /// <summary>
  /// Show the given message to the user in a dialog
  /// with just an OK button.
  /// </summary>
  public void Show(string pUserMessage)
  {
    MessageBox.Show(pUserMessage);
  }
  /// <summary>
  /// Show a message to the user with the specified
  /// window caption and buttons.
  /// </summary>
  public DialogResult Show(string pUserMessage, string pCaption,
    MessageBoxButtons pMessageBoxButtons)
  {
    return MessageBox.Show(pUserMessage, pCaption, pMessageBoxButtons);
  }
}

如果把這個代碼實現與之前創建服務的原則進行比較,我們會得到以下信息。

標準化服務約定:使用一個接口,所有的調用者都可以通過這個標準化的約定和服務進行交互。

松耦合:不存在對其他對象的綁定引用,所以這個服務不和其他的任何事務緊耦合。(有人可以辯稱它和System.Windows.Forms類緊耦合,因為我們使用MessageBox顯示消息。在這種情況下,耦合是可以接受的。)

抽象:真正顯示消息的方法是內部的,所以不能被外部方法訪問。唯一暴露的方法是在接口中指定的。

可自治性和可組合性:該服務不使用其他外部服務,所以它是自治的,也沒有對別的使用它的服務有所限定,所以DialogService是可組合的。

無狀態:該服務沒有任何內部變量,所以它是完全無狀態的。

我們的設計滿足了無狀態服務的所有標準,所以DialogService的類設計看上去非常不錯,開發者對它的使用不會受到緊耦合的約束。

主站蜘蛛池模板: 石柱| 监利县| 福建省| 武冈市| 抚顺县| 嵊泗县| 潞西市| 佛坪县| 收藏| 玉溪市| 霍林郭勒市| 湘潭市| 纳雍县| 岳阳市| 泉州市| 宁国市| 扶余县| 容城县| 桐梓县| 塔河县| 浦县| 东乡县| 积石山| 平果县| 凌源市| 宝鸡市| 大悟县| 大石桥市| 革吉县| 阳江市| 呼伦贝尔市| 绵阳市| 仙居县| 巫山县| 延安市| 福建省| 新巴尔虎右旗| 迭部县| 宁河县| 新建县| 东山县|