一、功能
根据前一篇博客:策略模式+单例模式+简单工厂模式:推送服务 ,想试用一下工厂模式:将之前的简单工厂模式格式化为工厂模式。
二、实现
修改前:简单工厂
public static class PushServiceFactory { public static IPush Creat(PushType type) { IPush pushService = null; switch (type) { case PushType.QQ: pushService = QQ.GetInstance(); break; case PushType.Email: pushService = new Email(); break; default:throw new ArgumentOutOfRangeException(); } return pushService; } }
public void ExcutePush(object data, List<PushType> types) { Console.WriteLine("推送数据"); foreach (PushType type in types) { IPush pushService = PushServiceFactory.Creat(type); pushService.Push(data); } }
修改后:工厂模式(象征性的都写在一个文件里面)
interface Factory { IPush Creat(); } public class QQFactory : Factory { public IPush Creat() { return QQ.GetInstance(); } } public class EmailFactory : Factory { public IPush Creat() { return new Email(); } }
interface Factory { IPush Creat(); } public class QQFactory:Factory { public IPush Creat() { return QQ.GetInstance(); } } public class EmailFactory : Factory { public IPush Creat() { return new Email(); } }
3、调用(这里有个前提:我不知道客户端是勾选了QQ推送还是Email推送)
所以在这里的调用,又回到了简单工厂模式,用简单工厂模式通过传参数,选择启用的推送工厂,进而实例具体的推送。
所以我觉得,简单工厂虽然有强耦合,但是我可以在不知道客户端需要调用谁的情况下,根据参数来实例化具体的类。
工厂模式,是我知道客户端明确的调用那个工厂来创建。
之前:简单工厂的调用
public void ExcutePush(object data, List<PushType> types) { Console.WriteLine("推送数据"); foreach (PushType type in types) { IPush pushService = PushServiceFactory.Creat(type); pushService.Push(data); } }
现在:工厂模式调用
public void ExcutePush(object data, List<PushType> types) { Console.WriteLine("推送数据"); foreach (PushType type in types) { Factory factory = null; switch (type) { case PushType.QQ: factory = new QQFactory(); break; case PushType.Email: factory = new EmailFactory(); break; default: throw new ArgumentOutOfRangeException(); } IPush pushService = factory.Creat(); pushService.Push(data); } }
4、总结
合适的才是最好的。