@TOC
前言
做项目的时候,用到了设计模式,总结下来,供以后参考,与诸君共勉。
一、代码中的部分片段
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace WindowsFormsCustomInfo { static class StepFactory { public static IStep GetStep(int stepIndex) { return _StepMap.ContainsKey(stepIndex) ? _StepMap[stepIndex] : null; }
private static readonly Dictionary<int, IStep> _StepMap = new Dictionary<int, IStep>() { {1,new MyStep1() }, {2,new MyStep2() }, {3,new MyStep3() }, }; } }
|
二、既然用到了,那么Head First系列或者设计模式之禅,不得拉出来掰扯掰扯嘛
1.使用new关键字进行实例化对象时是针对实现编程【相当于用new面向实现编程,让代码绑定了具体类,如下代码】,应该面向接口而不是面向实现,
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| ... IStep currentStep; if (stepIndex == 1) { currentStep = new MyStep1(); }else if(stepIndex == 2) { currentStep = new MyStep2(); }else if(stepIndex == 3) { currentStep = new MyStep3(); }... ...
|
- 违反了对扩展开放,对修改关闭:后期如果有新步骤要加入,而有些旧步骤不要了要删掉,那么就得改动这里多重分支判断
- 解决办法:找到变动的地方和不变的地方,不变的地方就是每个步骤要显示自己的步骤索引、调用IsLastStep判断是否是最后一步等,变动的就是if…else…中多个步骤对象实例化的部分。那么具体思路就是把变动的这部分单独放出去,把创建步骤的代码移到另一个对象中由这个新对象专职创建步骤对象,其他任何对象想要创建步骤就找这个对象就行,这个新对象就是工厂
2.简单工厂:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class SimpleStepFactory { public IStep CreateStep(string stepIndex) { IStep currentStep = null; if (stepIndex == 1) { currentStep = new MyStep1(); } else if (stepIndex == 2) { currentStep = new MyStep2(); } else if (stepIndex == 3) { currentStep = new MyStep3(); } return currentStep;
} }
|
- 符合单一职责,所有用户都用这个CreateStep方法来实例化新对象
3.静态工厂:利用静态方法定义一个简单的工厂,优点就是不需要使用创建对象的方法来实例化对象,但是缺点是不能通过继承来改变创建对象的行为
4.除了使用new操作符之外,还可以通过反射、工厂模式等方法制造对象实例
巨人的肩膀
- Head First 设计模式
- 设计模式之禅
- 公众号啦、OSCHINA啦、上面的有关设计模式的文章