简单工厂模式:就是店---很多糕点,你需要通过工厂来生成。目的是为了减少代码,先写一个父类,然后让子类继承这个父类,然后在写一个工厂类,根据switch来调用不同的子类。
测试的时候,直接调用工厂类即可。
直接上代码:
下面的算法是一个 计算器的实现:
-
using System;
-
using System.Collections.Generic;
-
using System.Linq;
-
using System.Text;
-
-
namespace DesignDemo
-
{
-
class Operation2
-
{
-
private
double _numberA;
-
private
double _numberB;
-
-
public
double numberA
-
{
-
get {return _numberA;}
-
set { _numberA = value; }
-
}
-
-
public
double numberB
-
{
-
get { return _numberB; }
-
set { _numberB = value; }
-
}
-
-
public
virtual
double GetResult()
-
{
-
double result = 0d;
-
return result;
-
}
-
}
-
-
class OperationAdd : Operation2
-
{
-
public
override
double GetResult()
-
{
-
double result = 0;
-
result = numberA + numberB;
-
return result;
-
}
-
}
-
-
class OperationSub : Operation2
-
{
-
public
override
double GetResult()
-
{
-
double result = 0;
-
result = numberA - numberB;
-
return result;
-
}
-
}
-
-
class OperationMul : Operation2
-
{
-
public
override
double GetResult()
-
{
-
double result = 0;
-
result = numberA * numberB;
-
return result;
-
}
-
}
-
-
class OperationDiv : Operation2
-
{
-
public
override
double GetResult()
-
{
-
double result = 0;
-
if (numberB == 0)
-
{
-
throw
new Exception("除数不能为0");
-
}
-
result = numberA / numberB;
-
return result;
-
}
-
}
-
-
-
/************************************************************************/
-
/* 建立简单工厂模式:减少耦合,把变化的东西封装成类 */
-
/************************************************************************/
-
-
class OperationFactory
-
{
-
public
static Operation2 createOperate(string operate)
-
{
-
Operation2 per = null;
-
switch (operate)
-
{
-
case "+":
-
per = new OperationAdd();
-
break;
-
case "-":
-
per = new OperationSub();
-
break;
-
case "*":
-
per = new OperationMul();
-
break;
-
case "/":
-
per = new OperationDiv();
-
break;
-
}
-
return per;
-
}
-
}
-
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:设计模式—简单工厂 - Python技术站