以支付为例
- UML图:
- 代码实现:
public interface IFactory
{
/// <summary>
/// 创建对象
/// </summary>
/// <returns></returns>
IPay CreateInterface();
}
public class WXPayFactory : IFactory
{
public IPay CreateInterface()
{
return new WXPay();
}
}
public class AliPayFactory : IFactory
{
public IPay CreateInterface()
{
return new AliPay();
}
}
public interface IPay
{
/// <summary>
/// 支付
/// </summary>
void Pay();
/// <summary>
/// 退款
/// </summary>
void Refund();
}
public class AliPay : IPay
{
public void Pay()
{
Console.WriteLine("支付宝支付");
}
public void Refund()
{
Console.WriteLine("支付宝退款");
}
}
public class WXPay : IPay
{
public void Pay()
{
Console.WriteLine("微信支付");
}
public void Refund()
{
Console.WriteLine("微信退款");
}
}
- 调用端代码:
class Program
{
static void Main(string[] args)
{
//微信支付
IPay payFactory = new WXPayFactory().CreateInterface();
payFactory.Pay();
payFactory.Refund();
Console.ReadLine();
}
}
- 总结:
工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
代码下载地址:链接:https://pan.baidu.com/s/1nzgnIEIBScBIRaEVvIn_SQ 1dg9