工厂方法模式(Factory Method)
工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
代码
我们依旧以之前的计算机程序来阐述工厂方法模式:
(不了解简单工厂的童鞋戳这里:http://blog.csdn.net/YongshuangZhao/article/details/78552102)
1.代码如下:
运算基类
using System;
namespace FactoryMethod
{
//运算符类
public class Operation
{
//数值1
private double numberA=0;
//数值2
private double numberB = 0;
public double NumberA
{
get { return numberA; }
set { numberA = value; }
}
public double NumberB
{
get { return numberB; }
set { numberB = value; }
}
//计算结果
public virtual double GetResult()
{
double result = 0;
return result;
}
}
}
加法类
using System;
namespace FactoryMethod
{
//加法类
public class OperationAdd:Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
}
减法类
using System;
namespace FactoryMethod
{
//减法类
public class OperationSub:Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA - NumberB;
return result;
}
}
}
乘法类
using System;
namespace FactoryMethod
{
//乘法类
public class OperationMul:Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA * NumberB;
return result;
}
}
}
除法类
using System;
namespace FactoryMethod
{
//除法类
public class OperationDiv:Operation
{
public override double GetResult()
{
double result = 0;
if (NumberB == 0)
throw new Exception ("除数不能为0。");
result = NumberA / NumberB;
return result;
}
}
}
工厂接口
using System;
namespace FactoryMethod
{
//工厂接口
public interface IFactory
{
Operation CreateOperation();
}
}
加法工厂类
using System;
namespace FactoryMethod
{
//加法工厂
public class AddFactory:IFactory
{
public Operation CreateOperation(){
return new OperationAdd ();
}
}
}
减法工厂类
using System;
namespace FactoryMethod
{
//减法类
public class SubFactory:IFactory
{
public Operation CreateOperation(){
return new OperationSub();
}
}
}
乘法工厂类
using System;
namespace FactoryMethod
{
//乘法类
public class MulFactory:IFactory
{
public Operation CreateOperation(){
return new OperationMul();
}
}
}
除法工厂类
using System;
namespace FactoryMethod
{
//除法类
public class DivFactory:IFactory
{
public Operation CreateOperation(){
return new OperationDiv ();
}
}
}
2.客户端代码,如下
客户端代码
using System;
namespace FactoryMethod
{
class MainClass
{
public static void Main (string[] args)
{
IFactory operationFactory = new AddFactory ();
Operation operation = operationFactory.CreateOperation ();
operation.NumberA = 1;
operation.NumberB = 2;
Console.WriteLine (operation.GetResult ());
operationFactory = new SubFactory ();
operation = operationFactory.CreateOperation ();
operation.NumberA = 1;
operation.NumberB = 2;
Console.WriteLine (operation.GetResult ());
}
}
}
3.运行结果
UML图
源码下载地址:https://gitee.com/ZhaoYongshuang/DesignPattern.git