参考了下网上的工厂模式实现,总的来说例子还是OK得,但是示例太单一了,因此我做了下优化的改良实现。
namespace DP
{
public interface ICreditCard
{
string GetCardType();
int GetCreditLimit();
int GetAnnualCharge();
}
//Concrete Product 1
public class MoneyBackCreditCard : ICreditCard
{
public string GetCardType()
=> "MoneyBack";
public int GetCreditLimit()
=> 15000;
public int GetAnnualCharge()
=> 500;
}
//Concrete Product 2
public class TitaniumCreditCard : ICreditCard
{
public string GetCardType()
=> "Titanium";
public int GetCreditLimit()
=> 25000;
public int GetAnnualCharge()
=> 1500;
}
//Concrete Product 3
public class PlatinumCreditCard : ICreditCard
{
public string GetCardType() => "Platinum";
public int GetCreditLimit() => 35000;
public int GetAnnualCharge() => 2000;
}
public abstract class CreditCardFactory
{
protected abstract ICreditCard MakeProduct();
public ICreditCard CreateCreditCard() => MakeProduct();
}
public class MoneyBackFactory : CreditCardFactory
{
protected override ICreditCard MakeProduct() => new MoneyBackCreditCard();
}
public class PlatinumFactory : CreditCardFactory
{
protected override ICreditCard MakeProduct() => new PlatinumCreditCard();
}
public class TitaniumFactory : CreditCardFactory
{
protected override ICreditCard MakeProduct() => new TitaniumCreditCard();
}
}
客户端调用:
ICreditCard CreditCardInstance = new PlatinumFactory().CreateCreditCard();
if (CreditCardInstance != null)
{
Console.WriteLine("CardType : " + CreditCardInstance.GetCardType());
Console.WriteLine("CreditLimit : " + CreditCardInstance.GetCreditLimit());
Console.WriteLine("AnnualCharge :" + CreditCardInstance.GetAnnualCharge());
}
else
{
Console.Write("Invalid Card Type");
}
Console.WriteLine("--------------");
CreditCardInstance = new MoneyBackFactory().CreateCreditCard();
if (CreditCardInstance != null)
{
Console.WriteLine("CardType : " + CreditCardInstance.GetCardType());
Console.WriteLine("CreditLimit : " + CreditCardInstance.GetCreditLimit());
Console.WriteLine("AnnualCharge :" + CreditCardInstance.GetAnnualCharge());
}
else
{
Console.Write("Invalid Card Type");
}
Console.Read();
参考资料:Factory Method Design Pattern in C#
相比较来讲,此示例更贴近实际的业务开发及逻辑,有助于理解工厂模式在业务开发中的应用。