C++设计模式-工厂模式
生活随笔
收集整理的這篇文章主要介紹了
C++设计模式-工厂模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
?
?
基本概念
代碼及實例
?
基本概念
工廠方法模式(Factory Method):定義一個用于創建對象的接口,讓字類決定實例化哪一個類。工廠方法使一個類的實例化延遲到其子類;
簡單工廠模式的最大優點在用戶工廠類中包含了必要的邏輯判斷,根據客戶端的選擇條件動態實例化相關的類,對于客戶端來說,去除了具體產品的依賴。
工廠方法模式實現時,客戶端需要決定實例化哪一個工廠來實現運算類,選擇判斷的問題還是存在的,也就是說,工廠方法把簡單工廠內部邏輯判斷移到了客戶端代碼來進行。
UML圖如下(這里以計算器為例)
?
代碼及實例
程序運行截圖如下:
源碼如下:
Head.h
#ifndef HEAD_H #define HEAD_H//運算相關 class Operation{public:double m_numberA;double m_numberB;virtual double getResult(); };class AddOperation: public Operation{public:AddOperation();double getResult(); };class MultiOperation: public Operation{public:MultiOperation();double getResult(); };//工廠相關class IFactory{public:virtual Operation *createOperation(); };class AddFactory: public IFactory{public:Operation *createOperation(); };class MultiFactory: public IFactory{public:Operation *createOperation(); };#endif //HEAD_HHead.cpp
#include "Head.h" #include <iostream> #include <string> using namespace std;Operation *IFactory::createOperation() {return nullptr; }Operation *AddFactory::createOperation() {return new AddOperation; }double Operation::getResult() {return -1; }AddOperation::AddOperation() {m_numberA = 0.0;m_numberB = 0.0; }double AddOperation::getResult() {return m_numberA + m_numberB; }MultiOperation::MultiOperation() {m_numberA = 0.0;m_numberB = 0.0; }double MultiOperation::getResult() {return m_numberA * m_numberB; }Operation * MultiFactory::createOperation() {return new MultiOperation; }main.cpp
#include "Head.h" #include <iostream> using namespace std;int main(int *argc, int *argv){IFactory *operAddFactory = new AddFactory;Operation *addOper = operAddFactory->createOperation();addOper->m_numberA = 100;addOper->m_numberB = 200;cout << "operAddFactory result is : " << addOper->getResult() << endl;delete operAddFactory;delete addOper;cout << "--------------- 華麗的分割線 ---------------" << endl;IFactory *operMultiFactory = new MultiFactory;Operation *multiOper = operMultiFactory->createOperation();multiOper->m_numberA = 12;multiOper->m_numberB = 5;cout << "operMultiFactory result is : " << multiOper->getResult() << endl;delete operMultiFactory;delete multiOper;getchar();return 0; }?
總結
以上是生活随笔為你收集整理的C++设计模式-工厂模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端笔记-对webpack和vue的基本
- 下一篇: Arduino笔记-使用独立电源给Ard