标签:over 解决 result bre strong example body public com
简单工厂模式(Simple Factory Pattern)的优点是,工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖
客户实例化对象时不需要关心该对象是由哪个子类实例化的。
IProduct接口:抽象产品类
ConcreteProduct类:产品类的具体实现
Simple Factory简单工厂类
一个简单计算器,具有简单的加操作和减操作。结构如下图所示
SimpleFactory:简单工厂类。
Operation:抽象操作类
AddOperation:加法操作
SubOperation:减法操作
1、抽象操作类Operation,及其具体实现类AddOperation、SubOperation |
/// <summary> /// 抽象操作类 /// </summary> public abstract class Operation { public int numberA; public int numberB; public abstract int GetResult(); } /// <summary> /// 加法操作 /// </summary> public class AddOperation : Operation { public override int GetResult() { return (this.numberA + this.numberB); } } /// <summary> /// 减法操作 /// </summary> public class SubOperation : Operation { public override int GetResult() { return (this.numberA - this.numberB); } } |
2、简单工厂类SimpleFactory |
/// <summary> /// 简单工厂类 /// </summary> public class SimpleFactory { public static Operation CreateOperation(string operation) { Operation o = null;
switch (operation) { case "+": o = new AddOperation(); break; case "-": o = new SubOperation(); break; } return o; } } |
3、客户端代码 |
static void Main(string[] args) { Operation operation1 = SimpleFactory.CreateOperation("+"); operation1.numberA = 10; operation1.numberB = 20; Console.WriteLine("{0}+{1}={2}", operation1.numberA, operation1.numberB, operation1.GetResult());
Operation operation2 = SimpleFactory.CreateOperation("-"); operation2.numberA = 10; operation2.numberB = 20; Console.WriteLine("{0}-{1}={2}", operation2.numberA, operation2.numberB, operation2.GetResult());
Console.Read(); } |
简单工厂模式是比较简单的一种设计模式,本文对此模式的概念及其设计结构图简单地进行了描述,最后以一个计算器的实例进行了说明。
转载自:http://www.cnblogs.com/ywqu/archive/2010/01/06/1640026.html
Net设计模式实例之简单工厂模式(Simple Factory Pattern)
标签:over 解决 result bre strong example body public com
原文地址:http://www.cnblogs.com/Wolfmanlq/p/6036039.html