大话设计模式--工厂方法模式 Factory Method -- C++实现
1. 工厂方法模式
定义一个用于创建对象的接口, 让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。
和简单工厂模式相比:
A: 简单工厂模式最大的优点在于工厂类中包含有必要的逻辑判断, 根据客户端的选择条件动态实例化相关的类,对客户端来说去除了与具体产品的依赖。
但缺点是 添加新产品时 需要修改工厂类 case, 违背了 "开放-封闭" 原则。
B: 工厂方法模式实现时,需要由客户端来决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在,只是由工厂类内部转移到客户端。
实例:
operation.h -- operation.cpp
#ifndef OPERATION_H #define OPERATION_H class Operation { public: Operation(); double virtual getResult(); double strA; double strB; double result; }; #endif // OPERATION_H
#include "operation.h" Operation::Operation() { strA = 0; strB = 0; result = 0; } double Operation::getResult() { return result; }
operationfunc.h operationfunc.cpp
#ifndef OPERATIONFUNC_H #define OPERATIONFUNC_H #include "operation.h" class OperationAdd : public Operation { public: double getResult(); }; class OperationSub : public Operation { public: double getResult(); }; class OperationMul : public Operation { public: double getResult(); }; class OperationDiv : public Operation { public: double getResult(); };
#include "operationfunc.h" double OperationAdd::getResult() { result = strA + strB; return result; } double OperationSub::getResult() { result = strA - strB; return result; } double OperationMul::getResult() { result = strA * strB; return result; } double OperationDiv::getResult() { result = strA / strB; return result; }
factory.h factory.cpp 抽象工厂
#ifndef FACTORY_H #define FACTORY_H #include "operation.h" #include "operationfunc.h" #include <string> using namespace std; class Factory { public: Factory(); virtual Operation* createOperation(); }; #endif // FACTORY_H
#include "factory.h" Factory::Factory() { } Operation* Factory::createOperation() {}
addfactory.h addfactory.cpp
#ifndef ADDFACTORY_H #define ADDFACTORY_H #include "factory.h" class AddFactory : public Factory { public: AddFactory(); Operation* createOperation(); }; #endif // ADDFACTORY_H
#include "addfactory.h" AddFactory::AddFactory() { } Operation* AddFactory::createOperation() { return new OperationAdd(); }
subfactory.h subfactory.cpp
#ifndef SUBFACTORY_H #define SUBFACTORY_H #include "factory.h" class SubFactory : public Factory { public: SubFactory(); Operation* createOperation(); }; #endif // SUBFACTORY_H
#include "subfactory.h" SubFactory::SubFactory() { } Operation* SubFactory::createOperation() { return new OperationSub(); }
main.cpp
#include <iostream> #include "operationfunc.h" #include "addfactory.h" #include "subfactory.h" using namespace std; int main() { cout << "Factory method " << endl; Factory *factory = new SubFactory(); Operation *oper = factory->createOperation(); oper->strA = 1.1; oper->strB = 2.3; cout << "result: " << oper->getResult() << endl; return 0; }