前言:设计模式看的不少,但是实际项目中使用(VisualStudio环境)Reshaper重构比较多,比如重命名,提取公共类,主要原因是好多业务不确定,
一开始大部分情况下都是先实现一个方法,该方法可以做为公共方法了才开始考虑重构,
本系列笔记主要记录:已经实现了功能的代码片段想要想改成某种实现模式怎么改最方便。
设计模式主要内容参考
https://www.runoob.com/design-pattern/factory-pattern.html
从工厂模式开始研究
1、工厂模式(Factory Pattern)是 最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
2、假如现在已经有了一个画矩形的类
class Rectangle { public void draw() { Console.WriteLine("Inside Rectangle::draw() method."); } }
3、提取接口
namespace FactoryPattern { internal interface IShape { void draw(); } class Rectangle : IShape { public void draw() { Console.WriteLine("Inside Rectangle::draw() method."); } } }
4、创建一个Circle类,接口为IShape
这里可以使用拷贝类
class Circle : IShape { public void draw() { Console.WriteLine("Inside Circle::draw() method."); } }
5、创建一个ShapeFactory
//使用 getShape 方法获取形状类型的对象 public IShape getShape(String shapeType) { if (shapeType == null) { return null; } if (shapeType.Equals("CIRCLE")) { return new Circle(); } else if (shapeType.Equals("RECTANGLE")) { return new Rectangle(); } return null; }
6、使用Factory如下
static void Main(string[] args) { ShapeFactory shapeFactory = new ShapeFactory(); shapeFactory.getShape("CIRCLE").draw(); shapeFactory.getShape("RECTANGLE").draw(); Console.ReadKey(); }
7、运行结果
原文:https://www.cnblogs.com/zhaogaojian/p/12491074.html