以支付为例
- UML图:
- 代码实现:
public class FactoryService
{
/// <summary>
/// 创建对象
/// </summary>
/// <param name="typeEnum">支付类型</param>
/// <returns></returns>
public static IPay CreateInterface(PayTypeEnum typeEnum)
{
switch (typeEnum)
{
case PayTypeEnum.WXPay:
return new WXPay();
case PayTypeEnum.AliPay:
return new AliPay();
default:
throw new Exception("支付类型传值有误");
}
}
}
/// <summary>
/// 支付类型
/// </summary>
public enum PayTypeEnum
{
/// <summary>
/// 微信支付
/// </summary>
WXPay,
/// <summary>
/// 支付宝支付
/// </summary>
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 payService = FactoryService.CreateInterface(PayTypeEnum.AliPay);
//IPay payService = FactoryService.CreateInterface(PayTypeEnum.WXPay);
payService.Pay();
payService.Refund();
Console.ReadKey();
}
}
- 总结:
简单工厂模式主要的核心是把创建对象转移到工厂类里面了,进行统一管理
代码下载地址:https://pan.baidu.com/s/1pMMwgmBDd4jvtI4IkoroVA iocy