工厂方法模式

前面实现计算器的简单工厂类是:

class Factory
{
    public static Operation SimpleFactory(string input)
    {
        Operation op = null;
        switch (input)
        {
            case "+":op = new OperationAdd();
                break;
            case "-":op = new OperationSub();
                break;
            case "*":op = new OperationMul();
                break;
            case "/":op = new OperationDiv();
                break;
        }
        return op;
    }
}

简单工厂最大优点:工厂类包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类。
当添加运算操作时,还是需要修改这个类里的switch;相当于,既对扩展开放,也对修改开放,违背 开放-封闭原则。

工厂方法模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
定义接口:

interface IFactory
{
    Operation CreateOperation();
}

各个运算的子类:

class SubFactory : IFactory
{
    public Operation CreateOperation()
    {
        return new OperationSub();
    }
}
class AddFactory : IFactory
{
    public Operation CreateOperation()
    {
        return new OperationAdd();
    }
}
class DivFactory : IFactory
{
    public Operation CreateOperation()
    {
        return new OperationDiv();
    }
}
class MulFactory : IFactory
{
    public Operation CreateOperation()
    {
        return new OperationMul();
    }
}

客户端实现:客户直接决定要哪个运算,而不是输入操作符再让程序内部判断。

IFactory operFactory = new AddFactory();
Operation op = operFactory.CreateOperation();
op.Num1 = 10;
op.Num2 = 20;
double result = op.GetResult();
Console.WriteLine(result);

Console.ReadKey();

优点:工厂方法把简单工厂内部逻辑判断移到了客户端代码来进行。你想要添加功能,本来是该工厂类的,现在添加对应的工厂子类与操作子类即可。


学雷锋例子:

雷锋类:

class LeiFeng
{
    public virtual void Sweep()
    {
        Console.WriteLine("扫地");
    }
    public void Wash()
    {
        Console.WriteLine("洗衣");
    }
    public void Cook()
    {
        Console.WriteLine("做饭");
    }
}

子类:

class Graduates:LeiFeng
{
    public override void Sweep()
    {
        Console.WriteLine("大学生扫地");
    }
}

class Volunteer:LeiFeng
{
    public override void Sweep()
    {
        Console.WriteLine("志愿者扫地");
    }
}

简单工厂:

class LeiFengFactory
{
    public static LeiFeng GetChild(string role)
    {
        LeiFeng lei = null;
        switch (role)
        {
            case "大学生":lei = new Graduates();
                break;
            case "志愿者":lei = new Volunteer();
                break;
        }
        return lei;
    }
}

工厂方法:

interface ILeiFactory
{
    LeiFeng GetLeiFeng();
}

class GetGraduates:ILeiFactory
{
    public LeiFeng GetLeiFeng()
    {
        return new Graduates();
    }
}

class GetVolunteer:ILeiFactory
{
    public LeiFeng GetLeiFeng()
    {
        return new Volunteer();
    }
}

客户端代码测试:

//LeiFeng leiFeng = LeiFengFactory.GetChild("志愿者");
ILeiFactory vol = new GetGraduates();
LeiFeng leiFeng = vol.GetLeiFeng();
leiFeng.Cook();
leiFeng.Sweep();
leiFeng.Wash();

Console.ReadKey();

你可能感兴趣的:(工厂方法模式)