简单工厂模式专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。
main.cc:
#include <windows.h> #include "simple_factory.h" /* design_pattern:"simple factory" */ int main(){ SimpleFactory *simple_factory = new SimpleFactory(); Watch *apple_watch = simple_factory->CreateWatch(APPLE_TYPE); Watch *huawei_watch = simple_factory->CreateWatch(HUAWEI_TYPE); apple_watch->ShowInformation(); huawei_watch->ShowInformation(); //clear delete simple_factory; delete apple_watch; delete huawei_watch; system("Pause"); return 0; }SimpleFactory:
//simple_factory.h #ifndef HELENDP_SOURCE_SIMPLE_FACTORY_H_ #define HELENDP_SOURCE_SIMPLE_FACTORY_H_ #include "watch.h" typedef enum{ APPLE_TYPE = 0, HUAWEI_TYPE }WatchType; class SimpleFactory{ public: SimpleFactory(); ~SimpleFactory(); Watch* CreateWatch(WatchType type); }; #endif //simple_factory.cc #include "simple_factory.h" #include "huawei_watch.h" #include "apple_watch.h" #include <stdio.h> SimpleFactory::SimpleFactory(){ } SimpleFactory::~SimpleFactory(){ } Watch* SimpleFactory::CreateWatch(WatchType type){ if (APPLE_TYPE == type) return new AppleWatch(); else if (HUAWEI_TYPE == type) return new HuaweiWatch(); else return NULL; }Watch:
//watch.h #ifndef HELENDP_SOURCE_WATCH_H_ #define HELENDP_SOURCE_WATCH_H_ class Watch{ public: Watch(); virtual ~Watch(); virtual void ShowInformation() = 0; }; #endif //watch.cc #include "watch.h" Watch::Watch(){ } Watch::~Watch(){ }AppleWatch:
//apple_watch.h #ifndef HELENDP_SOURCE_APPLE_WATCH_H_ #define HELENDP_SOURCE_APPLE_WATCH_H_ #include "watch.h" class AppleWatch : public Watch{ public: AppleWatch(); ~AppleWatch(); void ShowInformation(); }; #endif //apple_watch.cc #include "apple_watch.h" #include <iostream> using namespace std; AppleWatch::AppleWatch(){ } AppleWatch::~AppleWatch(){ } void AppleWatch::ShowInformation(){ cout << "Apple Watch Information!" <<endl; }HuaweiWatch:
//huawei_watch.h #ifndef HELENDP_SOURCE_HUAWEI_WATCH_H_ #define HELENDP_SOURCE_HUAWEI_WATCH_H_ #include "watch.h" class HuaweiWatch : public Watch{ public: HuaweiWatch(); ~HuaweiWatch(); void ShowInformation(); }; #endif //huawei_watch.cc #include "huawei_watch.h" #include <iostream> using namespace std; HuaweiWatch::HuaweiWatch(){ } HuaweiWatch::~HuaweiWatch(){ } void HuaweiWatch::ShowInformation(){ cout << "Huawei Watch Information" << endl; }代码和UML图(EA)工程文件,最后会整理打包上传.