码迷,mamicode.com
首页 > 其他好文 > 详细

简单工厂模式

时间:2016-04-01 17:58:14      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

简单工厂模式的本质是利用多态性,将实例化的过程交给工厂去完成,减少耦合度

实现加减乘除功能的计算器:

//操作类基类
public class Operation
{
public double NumberA { get; set; }
public double NumberB { get; set; }

public virtual double GetResult()
{
double result = 0;
return result;
}

}

//具体的操作类,实现各自的计算逻辑
public class OperationAdd : Operation
{
public override double GetResult()
{
return NumberA + NumberB;
}
}

public class OperationSub : Operation
{
public override double GetResult()
{
return NumberA - NumberB;
}
}

public class OperationMul : Operation
{
public override double GetResult()
{
return NumberA * NumberB;
}
}

public class OperationDiv : Operation
{
public override double GetResult()
{
if (NumberB==0)
{
throw new Exception("除数不能为0");
}
return NumberA / NumberB;
}
}

 

然后构造工厂类,根据客户端传入的参数,实例化不同的操作类,返回给调用者

public class OperationFactory
    {
        public static Operation CreateOperation(string operation)
        {
            Operation oper = null;
            switch (operation)
            {
                case "+": oper = new OperationAdd();
                    break;
                case "-": oper = new OperationSub();
                    break;
                case "*": oper = new OperationMul();
                    break;
                case "/": oper = new OperationDiv();
                    break;
                default:
                    oper = new Operation();
                    break;
            }
            return oper;
        }
    }

  客户端调用时,不需要认识所有的操作类,而只需要认识操作类的基类和工厂类即可:

 //乘法
 Operation operMutil = OperationFactory.CreateOperation("*");
 operMutil .NumberA = 3;
 operMutil .NumberB = 5;
 double mutilResult = operMutil .GetResult();

 //加法
 Operation operAdd = OperationFactory.CreateOperation("+");
 operAdd .NumberA = 3;
 operAdd .NumberB = 5;
 double addResult = operAdd .GetResult();

  

简单工厂模式

标签:

原文地址:http://www.cnblogs.com/angela217/p/5345649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!