C# 程式設計/設計模式
外觀
設計模式是為解決日常軟體問題而設計的通用構建塊。我們在日常生活中看到的某些基本術語和此類模式的示例。設計模式大體上分為 3 類
1. 建立型: 這些模式專為類例項化而設計。它們可以是類建立模式或物件建立模式。
2. 結構型: 這些模式是針對類的結構和組合而設計的。大多數這些模式的主要目標是增加所涉及的類(es)的功能,而無需對其組合進行太多更改。
3. 行為型: 這些模式是根據一個類如何與其他類通訊而設計的。
工廠模式是一種方法呼叫,它使用抽象類及其實現,為開發人員提供最適合工作的類。
讓我們先建立幾個類來演示如何使用它。這裡我們以銀行系統為例。
public abstract class Transaction
{
private string _sourceAccount;
// May not be needed in most cases, but may on transfers, closures and corrections.
private string _destinationAccount;
private decimal _amount;
public decimal Amount { get { return _amount; } }
private DateTime _transactionDate;
private DateTime _effectiveDate;
public Transaction(string source, string destination, decimal amount)
{
_sourceAccount = source;
_destinationAccount = destination;
_amount = amount;
_transactionDate = DateTime.Now;
}
public Transaction(string source, string destination, decimal amount, DateTime effectiveDate) : this(source, destination, amount)
{
_effectiveDate = effectiveDate;
}
protected decimal AdjustBalance(string accountNumber, decimal amount)
{
decimal newBalance = decimal.MinValue;
using(Mainframe.ICOMInterface mf = new Mainframe.COMInterfaceClass())
{
string dateFormat = DateTime.Now.ToString("yyyyMMdd HH:mm:ss");
mf.Credit(dateFormat, accountNumber, amount);
newBalance = mf.GetBalance( DateTime.Now.AddSeconds(1), accountNumber);
}
return newBalance;
}
public abstract bool Complete();
}
此 Transaction 類不完整,因為存在多種型別的交易
- 開戶
- 存款
- 取款
- 轉賬
- 罰款
- 更正
- 銷戶
對於此示例,我們將使用存款和取款部分,併為它們建立類。
public class Credit : Transaction
{
// Implementations hidden for simplicity
public override bool Complete()
{
this.AdjustBalance( _sourceAccount, amount);
}
}
public class Withdrawal : Transaction
{
// Implementations hidden for simplicity
public override bool Complete()
{
this.AdjustBalance( _sourceAccount, -amount);
}
}
問題是這些類做了很多相同的事情,因此如果我們可以只提供值,它就會確定我們需要的類型別,這將非常有用。因此,我們可以想出一些方法來區分不同型別的交易
- 正值表示存款。
- 負值表示取款。
- 有兩個帳號和一個正值表示轉賬。
- 有兩個帳號和一個負值表示銷戶。
- 等等。
所以,讓我們編寫一個新的類,其中包含一個靜態方法,該方法將為我們完成此邏輯,並將名稱結尾為 Factory
public class TransactionFactory
{
public static Transaction Create( string source, string destination, decimal amount )
{
if(!string.IsNullOrEmpty(destination) )
{
if(amount >= 0)
return new Credit( source, null, amount);
else
return new Withdrawal( source, null, amount);
}
else
{
// Other implementations here
}
}
}
現在,您可以使用此類來執行所有邏輯和處理,並確保您返回的型別是正確的。
public class MyProgram
{
static void Main()
{
decimal randomAmount = new Random().Next()*1000000;
Transaction t = TransactionFactory.Create("123456","",randomAmount);
// t.Complete(); <-- This would carry out the requested transaction.
Console.WriteLine("{0}: {1:C}",t.GetType().Name, t.Amount);
}
}
單例模式只例項化 1 個物件,並在整個程序生命週期中重複使用此物件。如果您希望物件保持狀態,或者設定物件需要大量資源,這將非常有用。以下是基本實現
public class MySingletonExample
{
private static object obj = new object();
private volatile static Hashtable _sharedHt;
public static Hashtable Singleton
{
get
{
if(_sharedHt == null){
lock(obj){
if(_sharedHt == null){
_sharedHt = new Hashtable();
}
}
}
return _sharedHt;
}
// set { ; }
// Not implemented for a true singleton
}
// Class implementation here..
}
Singleton 屬性將向所有呼叫者公開相同的例項。在第一次呼叫時,物件被初始化,並在後續呼叫中使用此物件。
此模式的示例包括
ConfigurationSettings(通用設定讀取器)HttpApplication(ASP .NET 中的應用程式物件)HttpCacheUtility(ASP .NET 中的快取物件)HttpServerUtility(ASP .NET 中的伺服器物件)