从设计模式的类型上来说,简单工厂模式是属于创建型模式,又叫做静态工厂方法(StaticFactory Method)模式,但不属于23种GOF 设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单实用的模式,可以理解为是不同工厂模式的一个特殊实现。 以下是以计算器为例的一个简单实现 运算类: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WindowsFormsApplication1 { /// <summary> /// 运算类 /// </summary> public class Operation { private double _numberA = 0; private double _numberB = 0; /// <summary> /// 数字A /// </summary> public double NumberA { get { return _numberA; } set { _numberA = value; } } /// <summary> /// 数字B /// </summary> public double NumberB { get { return _numberB; } set { _numberB = value; } } /// <summary> /// 虚方法 /// </summary> /// <returns></returns> public virtual double GetResult() { double result = 0; return result; } } } 加法类: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WindowsFormsApplication1 { /// <summary> /// 加法类(继承于运算类 Operation) /// </summary> public class OperationAdd : Operation { /// <summary> /// 重写父类方法 /// </summary> /// <returns></returns> public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } } 减法类: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WindowsFormsApplication1 { /// <summary> /// 减法类 /// </summary> public class OperationSub : Operation { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } } 乘法类: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WindowsFormsApplication1 { /// <summary> /// 乘法类 /// </summary> public class OperationMul : Operation { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } } } 除法类: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WindowsFormsApplication1 { /// <summary> /// 除法类 /// </summary> public class OperationDiv : Operation { public override double GetResult() { double result = 0; result = NumberA / NumberB; return result; } } } 简单运算工厂类: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WindowsFormsApplication1 { public class OperationFactry { public static Operation createOperate(string operate) { Operation oper = null; switch (operate) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; case "*": oper = new OperationMul(); break; case "/": oper = new OperationDiv(); break; default: break; } return oper; } } } 客户端代码: using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace WindowsFormsApplication1 { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }