代码改变世界

设计模式之工厂方法模式(FactoryMethod)

2010-01-18 13:47  key_sky  阅读(169)  评论(0编辑  收藏  举报

工厂方法模式(Factory Method):定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法是一个类的实例化延迟到其子类。
工厂方法是类的创建模式,定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类。

Factory1.cs:

代码
using System;
using System.Collections.Generic;
using System.Text;

//工厂方法模式(Factory Method):定义一个用于创建对象的接口,让子类决定实例化哪一个
//类,工厂方法是一个类的实例化延迟到其子类。
//工厂方法是类的创建模式,定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类。
namespace FactoryMethod
{
class Factory1
{
}
public class Operation
{
private double _numberA = 0;
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;
}
}

class OperationAdd : Operation
{
public override double GetResult()
{
double result = 0;
result
= NumberA + NumberB;
return result;
}
}

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

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

class OperationDiv : Operation
{
public override double GetResult()
{
double result = 0;
if (NumberB == 0)
throw new Exception("除数不能为0");
result
= NumberA / NumberB;
return result;
}
}
//工厂接口
interface IFactory
{
Operation CreateOperation();
}
//具体工厂接口
class AddFactory : IFactory
{
public Operation CreateOperation()
{
return new OperationAdd();
}
}
class SubFactory : IFactory
{
public Operation CreateOperation()
{
return new OperationSub();
}
}
class MulFactory : IFactory
{
public Operation CreateOperation()
{
return new OperationMul();
}
}
class DivFactory : IFactory
{
public Operation CreateOperation()
{
return new OperationDiv();
}
}
}

Program.cs:

代码
using System;
using System.Collections.Generic;
using System.Text;

namespace FactoryMethod
{
class Program
{
static void Main(string[] args)
{
IFactory operFactory
= new AddFactory();
Operation oper
= operFactory.CreateOperation();
oper.NumberA
= 1;
oper.NumberB
= 2;
double result = oper.GetResult();
Console.WriteLine(result);
Console.Read();
}
}
}

运行结果:

3