设计模式-抽象工厂模式(二)
计算器实例
1.运算基类
public class OperateBase { private float _number = 0.0f; private float _secondnumber = 0.0f; public float Number { get { return _number; } set { _number = value; } } public float Secondnumber { get { return _secondnumber; } set { _secondnumber = value; } } public virtual float ComputeResult() { return 0; } }
2.运算结果类
public class MulOperate:OperateBase { public override float ComputeResult() { return Number / Secondnumber; } }
3.加法运算结果
public class AddOperate:OperateBase { public override float ComputeResult() { return Number+Secondnumber; } }
4.减法运算结果
public class SubOperate:OperateBase { public override float ComputeResult() { return Number - Secondnumber; } }
5.乘法运算结果
public class DivOperate:OperateBase { public override float ComputeResult() { return Number*Secondnumber; } }
6.除法运算结果
public class MulOperate:OperateBase { public override float ComputeResult() { return Number / Secondnumber; } }
7.抽象工厂
public interface IFactory { OperateBase CreateOperate(); }
8.加法实现
public class AddFactory : IFactory { public OperateBase CreateOperate() { return new AddOperate(); } }
9.减法实现
public class SubFactory : IFactory { public OperateBase CreateOperate() { return new SubOperate(); } }
10.乘法实现
public class DivFactory : IFactory { public OperateBase CreateOperate() { return new DivOperate(); } }
11.除法实现
public class MulFactory : IFactory { public OperateBase CreateOperate() { return new MulOperate(); } }
12.调用
IFactory facotry = new DivFactory(); OperateBase add = facotry.CreateOperate(); add.Number = 1; add.Secondnumber = 1; Console.WriteLine(add.ComputeResult());