《大话设计模式》学习笔记1:简单工厂模式
计算器示例:
1.运算类:
public class Operation { public double NumberA { get; set; } public double NumberB { get; set; } public virtual double GetResult() {
return 0; } }
2.加减乘除类(以加法类为例):
public class AddOperation:Operation { public override double GetResult() { return NumberA + NumberB; } }
3.简单工厂类:
public class OperationFactory { public static Operation CreateOperate(string operate) { Operation operation; switch(operate) { case "+": operation = new AddOperation(); break; case "-": operation = new SubOperation(); break; default : operation = null; break; } return operation; } }
4.客户端代码:
class Program { static void Main(string[] args) { Operation operation = OperationFactory.CreateOperate("+"); oper.NumberA = 1; oper.NumberB = 2; Console.WriteLine(operation.GetResult()); } }
posted on 2015-05-08 10:19 Walden1024 阅读(329) 评论(0) 编辑 收藏 举报