
设计模式 - 6) 工厂模式
发布日期:2021-05-13 19:47:06
浏览次数:21
分类:博客文章
本文共 2608 字,大约阅读时间需要 8 分钟。
前面讲到的简单工厂如下面这段代码,后续需要拓展功能时,需要在简单工厂里面添加 case ,这依旧违反了开放-封闭中的对修改关闭的原则。
// 工厂生成对象类public class OperationFactory{ public static OperationClass GetOperation(string operationType) { OperationClass opera = null; switch (operationType) { case "+": opera = new AddOperation(); break; case "-": opera = new SubOperation(); break; case "*": opera = new MulOperation(); break; case "/": opera = new DivOperation(); break; case "sqrt": opera = new SqrtOperation(); break; case "squa": opera = new SquareOperation(); break; default: break; } return opera; }}
一、将一个雷锋的简单工厂修改成工厂模式
1. 简单工厂实现代码
public class LeiFeng{ public void Sweep() { Console.WriteLine("扫地"); } public void Wash() { Console.WriteLine("洗衣"); } public void BuyRice() { Console.WriteLine("买米"); }}public class Undergraduate : LeiFeng { }public class Volunteer : LeiFeng { }public class SimpleFactory{ public static LeiFeng CreateLeiFeng(string type) { LeiFeng result = null; switch (type) { case "big student": result = new Undergraduate(); break; case "volunteer": result = new Volunteer(); break; default: break; } return result; }}LeiFeng studentA = SimpleFactory.CreateLeiFeng("big student");studentA.Sweep();LeiFeng studentB = SimpleFactory.CreateLeiFeng("big student");studentB.Wash();LeiFeng studentC = SimpleFactory.CreateLeiFeng("big student");studentC.BuyRice();
2. 工厂模式实现代码
结构是这样的
sequenceDiagramCreator->>Product: 创造生产者ConcreteCreator->>ConcreteProduct: 工厂创造生产者ConcreteCreator->>Creator: 继承ConcreteProduct->>Product: 继承
public interface IFactory{ LeiFeng CreateLeiFeng();}public class UndergraduateFactory : IFactory{ public LeiFeng CreateLeiFeng() { return new Undergraduate(); }}public class VolunteerFactory : IFactory{ public LeiFeng CreateLeiFeng() { return new Volunteer(); }} IFactory factory = new UndergraduateFactory();LeiFeng lf = factory.CreateLeiFeng();lf.Sweep();lf.Wash();lf.BuyRice();
后面要改只需要改第一行:IFactory factory = new UndergraduateFactory();
3. 你可能会说,那工厂其实没什么作用,直接一句不就可以了:
LeiFeng lf = new Undergraduate();
结构如下
graph LRConcreteProduct--继承-->Product
这不够规范,而且工厂模式可以结合单例模式。
发表评论
最新留言
留言是一种美德,欢迎回访!
[***.207.175.100]2025年05月03日 13时14分46秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
常量池、运行时常量池
2019-03-11
3、条件查询
2019-03-11
5、分组函数 / 聚合函数
2019-03-11
8、子查询
2019-03-11
cordova打包apk更改图标
2019-03-11
开启与配置SMTP服务器
2019-03-11
域名解析步骤
2019-03-11
APP卡片式设计
2019-03-11
GitHub上传时,项目在已有文档时直接push出现错误解决方案
2019-03-11
云数据库
2019-03-11
图计算
2019-03-11
大数据在不同领域的应用
2019-03-11
页面置换算法
2019-03-11
推荐系统资料
2019-03-11
文件系统的层次结构
2019-03-11
减少磁盘延迟时间的方法
2019-03-11
vue(渐进式前端框架)
2019-03-11
权值初始化和与损失函数
2019-03-11
案例讨论
2019-03-11
传输层基本功能
2019-03-11