- 軟件再工程:優化現有軟件系統的方法與最佳實踐
- (美)Bradley Irby
- 574字
- 2020-11-04 16:44:58
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的類設計看上去非常不錯,開發者對它的使用不會受到緊耦合的約束。