设计模式之-工厂方法
工厂方法模式(Factory Method)
定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延续到其子类中。
工厂方法模式是简单工厂的扩展,工厂方法把简单工厂的内部逻辑判断转移到了客户端进行,想要增加功能,以前是修改工厂类,现在是修改客户端。
工厂方法模式克服了简单工厂违背开放-封闭原则(软件实体应该可以扩展,但是不可以修改)的缺点,又保持了封装对象创建过程的优点。但缺点是每加一个产品,就需要加一个产品工厂的类,增加额外的开发。
public class Operation { private double _numberA = 0; private double _numberB = 0; public double NumberA { get; set; } public double NumberB { get; set; } 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; } } interface IFactory { Operation CreateOperation(); } class AddFactory:IFactory { public Operation CreateOperation() { return new OperationAdd(); } } class DivFactory { public Operation CreateOperation() { return new OperationDiv(); } } //以下是客户端内代码 static void Main(string[] args) { IFactory operFactory = new AddFactory();//工厂方法模式 Operation oper = operFactory.CreateOperation(); oper.NumberA = 4; oper.NumberB = 2; double result = oper.GetResult(); Console.WriteLine(result); Console.Read(); }
UML类图
C++的工厂方法模式如下:
#include<iostream> #include<string> using namespace std; class Producer { protected: string brand; public: virtual void output() { cout << brand << "---" << "的产品" << endl; } }; class Haier :public Producer { protected: string brand = "Haier"; public: virtual void output() { cout<<brand<<endl; } }; class Midea :public Producer { protected: string brand = "Mieda"; public: virtual void output() { cout << brand << endl; } }; class Factory { public: virtual Producer* producer() = 0; }; class FactoryHaier :public Factory { public: Producer* producer() { return new Haier; } }; class FactoryMidea :public Factory { public: Producer* producer() { return new Midea; } }; int main() { FactoryHaier* fh = new FactoryHaier(); FactoryMidea* fm = new FactoryMidea(); Producer* pro = fh->producer(); pro->output(); pro = fm->producer(); pro->output(); return 0; }