commit 22124bb82778430a14c1c2f59254232fe11683b1 Author: hit_lu Date: Mon Jun 2 13:57:29 2025 +0800 设计模式例程 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c795b05 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +build \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..c53488f --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,20 @@ +cmake_minimum_required(VERSION 3.16.0) + +project(design-pattern) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + + +set(SOURCE_DIR "${PROJECT_SOURCE_DIR}/src") +set(INCLUDE_DIR "${PROJECT_SOURCE_DIR}/inc") + +file(GLOB SOURCES "${SOURCE_DIR}/*.cpp") +file(GLOB HEADERS "${INCLUDE_DIR}/*.hpp") + +aux_source_directory(${SOURCE_DIR} src) +aux_source_directory(${INCLUDE_DIR} inc) + +add_executable(design-pattern ${SOURCES} ${HEADERS} "${PROJECT_SOURCE_DIR}/main.cpp") + +target_include_directories(design-pattern PRIVATE ${SOURCE_DIR} ${INCLUDE_DIR}) diff --git a/inc/abstract_factory.hpp b/inc/abstract_factory.hpp new file mode 100644 index 0000000..b329fae --- /dev/null +++ b/inc/abstract_factory.hpp @@ -0,0 +1,79 @@ +#pragma once +#include "common.hpp" + +class Shape // ״ӿ +{ +public: + virtual void draw() = 0; + +}; + +class Rectangle :public Shape +{ +public: + void draw(); +}; + +class Square :public Shape +{ +public: + void draw(); +}; + +class Circle :public Shape +{ +public: + void draw(); +}; + +class Color // ɫӿ +{ +public: + virtual void fill() = 0; + +}; + +class Red :public Color +{ +public: + void fill(); +}; + +class Green :public Color +{ +public: + void fill(); +}; + +class Yellow :public Color +{ +public: + void fill(); +}; + +class AbstractFactory +{ +public: + virtual Color* getColor(string color) = 0; + virtual Shape* getShape(string shape) = 0; +}; + +class ShapeFactory :public AbstractFactory +{ +public: + Shape* getShape(string shape); + Color* getColor(string color); +}; + +class ColorFactory :public AbstractFactory +{ +public: + Shape* getShape(string shape); + Color* getColor(string color); +}; + +class FactoryProducer +{ +public: + AbstractFactory* getFactory(string choice); +}; \ No newline at end of file diff --git a/inc/chain_of_responsibility.hpp b/inc/chain_of_responsibility.hpp new file mode 100644 index 0000000..f866dac --- /dev/null +++ b/inc/chain_of_responsibility.hpp @@ -0,0 +1,74 @@ +#pragma once +#include "common.hpp" + +class Manager; + +class PersonA // Requester ݣ +{ +public: + PersonA(string name, int dayoff, string reason) : + m_Name(name), m_Dayoff(dayoff), m_Reason(reason) { + m_pLeader = nullptr; + }; + + int getDayoff(); + string getName(); + string getReason(); + void setLeader(Manager* pLeader); + void Request(); + +private: + int m_Dayoff; + string m_Name; + string m_Reason; + Manager* m_pLeader; +}; + +class Manager // Resonsible ˳ +{ +public: + + Manager(string name, string title) :m_Name(name), m_Title(title) + { + m_pNextHandle = nullptr; + }; + + string getName(); + string getTitle(); + void setNextHander(Manager* p_NextHandler); + virtual void handleRequest(PersonA* pPerson) = 0; + +protected: + string m_Name; + string m_Title; + Manager* m_pNextHandle; + +}; + +class Supervisor :public Manager // +{ +public: + Supervisor(string name, string title) :Manager(name, title) {}; + void handleRequest(PersonA* pPerson); +}; + +class DepartmentManager :public Manager +{ +public: + DepartmentManager(string name, string title) :Manager(name, title) {}; + void handleRequest(PersonA* pPerson); +}; + +class CEO :public Manager +{ +public: + CEO(string name, string title) :Manager(name, title) {}; + void handleRequest(PersonA* pPerson); +}; + +class Administrator :public Manager +{ +public: + Administrator(string name, string title) :Manager(name, title) {}; + void handleRequest(PersonA* pPerson); +}; \ No newline at end of file diff --git a/inc/combination.hpp b/inc/combination.hpp new file mode 100644 index 0000000..de3afc7 --- /dev/null +++ b/inc/combination.hpp @@ -0,0 +1,102 @@ +#pragma once +#include "common.hpp" + +class ComputerComponent +{ +public: + ComputerComponent(string name) :m_name(name) {} + virtual void showInfo(string indent = "") = 0; + virtual bool isComposite(); + virtual void startup(string indent = ""); + virtual void shutdown(string indent = ""); + +protected: + string m_name; +}; + +class CPU :public ComputerComponent +{ +public: + CPU(string name) :ComputerComponent(name) {} + void showInfo(string indent); +}; + +class MemoryCard :public ComputerComponent +{ +public: + MemoryCard(string name) :ComputerComponent(name) {} + void showInfo(string indent); +}; + +class HardDisk :public ComputerComponent +{ +public: + HardDisk(string name) :ComputerComponent(name) {} + void showInfo(string indent); +}; + +class GraphicsCard :public ComputerComponent +{ +public: + GraphicsCard(string name) :ComputerComponent(name) {} + void showInfo(string indent); +}; + +class Battery :public ComputerComponent +{ +public: + Battery(string name) :ComputerComponent(name) {} + void showInfo(string indent); +}; + +class Fan :public ComputerComponent +{ +public: + Fan(string name) :ComputerComponent(name) {} + void showInfo(string indent); +}; + +class Displayer :public ComputerComponent +{ +public: + Displayer(string name) :ComputerComponent(name) {} + void showInfo(string indent); +}; + +class ComputerCompsite :public ComputerComponent +{ +public: + ComputerCompsite(string name) :ComputerComponent(name) {}; + void showInfo(string indent); + bool isComposite(); + + void addComponent(ComputerComponent* component); + void removeComponent(ComputerComponent* component); + + void startup(string indent); + void shutdown(string indent); + +private: + vector m_components; // ɳɷ +}; + +class Mainboard :public ComputerCompsite +{ +public: + Mainboard(string name) :ComputerCompsite(name) {}; + void showInfo(string indent); +}; + +class ComputerCase :public ComputerCompsite +{ +public: + ComputerCase(string name) :ComputerCompsite(name) {}; + void showInfo(string indent); +}; + +class Computer :public ComputerCompsite +{ +public: + Computer(string name) :ComputerCompsite(name) {}; + void showInfo(string indent); +}; \ No newline at end of file diff --git a/inc/common.hpp b/inc/common.hpp new file mode 100644 index 0000000..88544b2 --- /dev/null +++ b/inc/common.hpp @@ -0,0 +1,18 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + diff --git a/inc/decorate.hpp b/inc/decorate.hpp new file mode 100644 index 0000000..acdcc7b --- /dev/null +++ b/inc/decorate.hpp @@ -0,0 +1,96 @@ +#pragma once +#include "common.hpp" + +class Person +{ +public: + virtual void wear(); + +protected: + string m_Name; +}; + +class Engineer :public Person +{ +public: + Engineer(string name, string skill) :m_Name(name), m_Skill(skill) {}; + string getSkill(); + virtual void wear(); + +private: + string m_Skill; + string m_Name; +}; + +class Teacher :public Person +{ +public: + Teacher(string name, string title) :m_Name(name), m_Title(title) {}; + string getTitle(); + virtual void wear(); + +private: + string m_Name; + string m_Title; +}; + +class ClothingDecorator :public Person +{ +public: + ~ClothingDecorator(); + + virtual void wear(); + virtual void decorate() = 0; + + +protected: + Person* m_pPerson; // ָ + +}; + +class CasualPantDecorator :public ClothingDecorator +{ +public: + CasualPantDecorator(Person* pPerson) { this->m_pPerson = pPerson; }; + virtual void decorate(); + +}; + +class BeltDecorator :public ClothingDecorator +{ +public: + BeltDecorator(Person* pPerson) { this->m_pPerson = pPerson; }; + virtual void decorate(); +}; + +class LeatherShoesDecorator :public ClothingDecorator +{ +public: + LeatherShoesDecorator(Person* pPerson) { this->m_pPerson = pPerson; }; + virtual void decorate(); + +}; + +class KnittedSweaterDecorator :public ClothingDecorator +{ +public: + KnittedSweaterDecorator(Person* pPerson) { this->m_pPerson = pPerson; }; + virtual void decorate(); + +}; + +class WhiteShirtDecorator :public ClothingDecorator +{ +public: + WhiteShirtDecorator(Person* pPerson) { this->m_pPerson = pPerson; }; + virtual void decorate(); + +}; + +class GlassesDecorator :public ClothingDecorator +{ +public: + GlassesDecorator(Person* pPerson) { this->m_pPerson = pPerson; }; + virtual void decorate(); + +}; \ No newline at end of file diff --git a/inc/design_pattern.hpp b/inc/design_pattern.hpp new file mode 100644 index 0000000..16c27dd --- /dev/null +++ b/inc/design_pattern.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include "observe.hpp" // ۲/ģʽ +#include "state.hpp" // ״̬ģʽ +#include "decorate.hpp" // װģʽ +#include "singleton.hpp" // ģʽ +#include "prototype.hpp" // ԭģʽ +#include "chain_of_responsibility.hpp" // ģʽ +#include "proxy.hpp" // ģʽ +#include "facade.hpp" // ģʽ +#include "iterator.hpp" // ģʽ +#include "combination.hpp" // ģʽ +#include "strategy.hpp" // ģʽ +#include "simple_factory.hpp" // 򵥹ģʽ +#include "abstract_factory.hpp" // 󹤳ģʽ + +void RunObserveMode(void); +void RunStateMode(void); +void RunDecorateMode(void); +void RunSingletonMode(void); +void RunPrototypeMode(void); +void RunChainOfResponsibilityMode(void); +void RunProxyMode(void); +void RunFacadeMode(void); +void RunIteratorMode(void); +void RunCombination(void); +void RunStrategyMode(void); +void RunSimpleFactoryMode(void); +void RunAbstractFactoryMode(void); \ No newline at end of file diff --git a/inc/facade.hpp b/inc/facade.hpp new file mode 100644 index 0000000..ebc1b54 --- /dev/null +++ b/inc/facade.hpp @@ -0,0 +1,37 @@ +#pragma once +#include "common.hpp" + +class ZIPModel +{ +public: + void compress(string srcFilePath, string dstFilePath); + void decompress(string srcFilePath, string dstFilePath); +}; + +class RARModel +{ +public: + void compress(string srcFilePath, string dstFilePath); + void decompress(string srcFilePath, string dstFilePath); +}; + +class ZModel +{ +public: + void compress(string srcFilePath, string dstFilePath); + void decompress(string srcFilePath, string dstFilePath); +}; + +class CompressionFacade +{ +public: + CompressionFacade(ZIPModel* pZipModel = nullptr, RARModel* pRarModel = nullptr, ZModel* pZModel = nullptr); + ~CompressionFacade(); + void compress(string srcFilePath, string dstFilePath, string type); + void decompress(string srcFilePath, string dstFilePath); + +private: + ZIPModel* m_pZipModel; + RARModel* m_pRarModel; + ZModel* m_pZModel; +}; \ No newline at end of file diff --git a/inc/iterator.hpp b/inc/iterator.hpp new file mode 100644 index 0000000..112a263 --- /dev/null +++ b/inc/iterator.hpp @@ -0,0 +1,152 @@ +#pragma once +#include "common.hpp" + +class NumeralSystem; + +class Customer +{ +public: + Customer(string name, string clinics = "None") :m_name(name), m_clinics(clinics) + { + m_num = 0; + } + string getName(); + void Regist(NumeralSystem* system); + void setNum(int num); + int getNum(); + void setClinic(string clinic); + string getClinic(); + +private: + string m_name; + int m_num; + string m_clinics; +}; + +class NumeralIterator +{ +public: + NumeralIterator(vector data, int curIdx = -1) :m_data(data), m_curIdx(curIdx) {}; + bool next(); + Customer* current(); + +private: + vector m_data; + int m_curIdx; +}; + +class NumeralSystem +{ +public: + static vector m_clinics; + NumeralSystem(string name) : m_name(name) + { + m_curNum = 0; + } + void pushCustomer(Customer* pCustomer); + NumeralIterator getIterator(); + +private: + vector m_pCustomers; + int m_curNum; + string m_name; +}; + +// ======================== ģʽԴ磩 ==================== + +class Iterator +{ +public: + Iterator() {}; + virtual ~Iterator() {}; + virtual string toBegin() = 0; + virtual string toNext() = 0; + virtual string getCurrent() = 0; + virtual bool isEnd() = 0; +}; + +class Aggregate +{ +public: + virtual int Count() = 0; + virtual void Push(const string& strValue) = 0; + virtual string Pop(const int nIndex) = 0; + virtual Iterator* CreateIterator() = 0; +}; + +class ConcreteIterator : public Iterator +{ +public: + ConcreteIterator(Aggregate* pAggregate) :m_nCurrent(0), Iterator() + { + m_Aggregate = pAggregate; + } + string toBegin() + { + return m_Aggregate->Pop(0); + } + string toNext() + { + string strRet; + m_nCurrent++; + if (m_nCurrent < m_Aggregate->Count()) + { + strRet = m_Aggregate->Pop(m_nCurrent); + } + return strRet; + } + string getCurrent() + { + return m_Aggregate->Pop(m_nCurrent); + } + bool isEnd() + { + return ((m_nCurrent >= m_Aggregate->Count()) ? true : false); + } +private: + Aggregate* m_Aggregate; + int m_nCurrent; +}; + +class ConcreteAggregate : public Aggregate +{ +public: + ConcreteAggregate() :m_pIterator(NULL) + { + m_vecItems.clear(); + } + ~ConcreteAggregate() + { + if (NULL != m_pIterator) + { + delete m_pIterator; + m_pIterator = NULL; + } + } + Iterator* CreateIterator() + { + if (NULL == m_pIterator) + { + m_pIterator = new ConcreteIterator(this); + } + return m_pIterator; + } + void Push(const string& strValue) + { + m_vecItems.push_back(strValue); + } + string Pop(const int nIndex) + { + string strRet; + if (nIndex < m_vecItems.size()) + { + strRet = m_vecItems[nIndex]; + } + return strRet; + } +private: + vector m_vecItems; + Iterator* m_pIterator; + + +}; \ No newline at end of file diff --git a/inc/observe.hpp b/inc/observe.hpp new file mode 100644 index 0000000..abe0850 --- /dev/null +++ b/inc/observe.hpp @@ -0,0 +1,39 @@ +#pragma once +#include "common.hpp" + +class WaterHeater; + +class Observer // ۲ߵij +{ +public: + virtual void Update(WaterHeater* waterHeater) const = 0; +}; + +class WashingMode :public Observer // ۲ +{ +public: + virtual void Update(WaterHeater* waterHeater) const; +}; + +class DrinkingMode :public Observer // ۲ +{ +public: + virtual void Update(WaterHeater* waterHeater) const; +}; + +class WaterHeater // ۲ +{ +public: + WaterHeater(int temperature = 25) :m_temperature(temperature) {}; + + int getTempetature(); + void setTemperature(int temperature); + + virtual void HandleObserver(); // ֪ͨ۲ + bool RegisterObserver(Observer* inObserver); // Ӽ۲죩 + bool UnRegisterObserver(Observer* inObserver); // ɾ۲죩 + +protected: + int m_temperature; + vector m_Observers; +}; diff --git a/inc/prototype.hpp b/inc/prototype.hpp new file mode 100644 index 0000000..0cd49a0 --- /dev/null +++ b/inc/prototype.hpp @@ -0,0 +1,22 @@ +#pragma once +#include "common.hpp" + +class Prototype // C++ ĿΪdzԭģʽΪ +{ +public: + Prototype() {} + ~Prototype() {} + + virtual Prototype* Clone() = 0; +}; + +class ConcretePrototype :public Prototype +{ +public: + ConcretePrototype() {} + ~ConcretePrototype() {} + + virtual Prototype* Clone(); +private: + ConcretePrototype(const ConcretePrototype&); // +}; \ No newline at end of file diff --git a/inc/proxy.hpp b/inc/proxy.hpp new file mode 100644 index 0000000..071914e --- /dev/null +++ b/inc/proxy.hpp @@ -0,0 +1,33 @@ +#pragma once +#include "common.hpp" + +class Subject // ij +{ +public: + Subject(string name) :m_Name(name) {}; + string getName(); + virtual void request() = 0; + +private: + string m_Name; +}; + +class RealSubject :public Subject // +{ +public: + RealSubject(string name) :Subject(name) {}; + void request(); + +}; + +class ProxySubject :public Subject // +{ +public: + ProxySubject(string name, RealSubject* subject = nullptr) :Subject(name), m_pSubject(subject) {}; + void request(); + void preRequest(); + void afterRequest(); + +private: + RealSubject* m_pSubject; +}; \ No newline at end of file diff --git a/inc/simple_factory.hpp b/inc/simple_factory.hpp new file mode 100644 index 0000000..3bbb54c --- /dev/null +++ b/inc/simple_factory.hpp @@ -0,0 +1,50 @@ +#pragma once +#include "common.hpp" + +typedef enum // +{ + PenTypeLine = 1, + PenTypeRect = 2, + PenTypeEllipse = 3 + +}PenType; + +class Pen +{ +public: + Pen(string name); + virtual PenType getType() = 0; + string getName(); +private: + string m_name; +}; + +class LinePen :public Pen +{ +public: + LinePen(string name) :Pen(name) {} + PenType getType(); +}; + +class RectanglePen :public Pen +{ +public: + RectanglePen(string name) :Pen(name) {} + PenType getType(); +}; + +class EllipsePen :public Pen +{ +public: + EllipsePen(string name) :Pen(name) {} + PenType getType(); +}; + +class PenFactory +{ +public: + PenFactory() {}; + Pen* CreatePen(PenType pentype); +private: + map m_PenProduct; +}; diff --git a/inc/singleton.hpp b/inc/singleton.hpp new file mode 100644 index 0000000..bfbde13 --- /dev/null +++ b/inc/singleton.hpp @@ -0,0 +1,29 @@ +#pragma once +#include "common.hpp" + +class SingletonA // ʽ̲߳ȫռ任ʱ +{ +private: + SingletonA() {} // 캯˽л֤󲻻ⱻ + + SingletonA(SingletonA&) = delete; + SingletonA& operator=(const SingletonA&) = delete; + + static SingletonA* m_pInstance; +public: + static SingletonA* getInstance(); + +}; + +class SingletonB // ʽ̰߳ȫʱ任ռ +{ +private: + SingletonB() {} + SingletonB(SingletonB&) = delete; + SingletonB& operator=(const SingletonB&) = delete; +public: + static SingletonB* getInstance(); + +}; + + diff --git a/inc/state.hpp b/inc/state.hpp new file mode 100644 index 0000000..fd56dc8 --- /dev/null +++ b/inc/state.hpp @@ -0,0 +1,74 @@ +#pragma once +#include "common.hpp" + +class State; +class Context // Ļ࣬״̬л +{ +public: + Context(); + ~Context(); + + void addState(State* state); + bool changeState(State* state); + State* getState(); + void setStateInfo(int stateInfo); + int getStateInfo(); + +private: + State* p_curState; + vector p_states; + int m_stateInfo; +}; + +class Water; + +class State +{ +public: + State(string name) :m_name(name) {}; + virtual void behavior(Water* p_water) const = 0; + virtual bool isMatch(int stateInfo) const = 0; + string getName(); + +private: + string m_name; +}; + + +class SolidState :public State +{ +public: + SolidState(string name) :State(name) {}; + void behavior(Water* p_water) const; + bool isMatch(int stateInfo) const; +}; + +class Liquidtate :public State +{ +public: + Liquidtate(string name) :State(name) {}; + void behavior(Water* p_water) const; + bool isMatch(int stateInfo) const; +}; + +class GaseousState :public State +{ +public: + GaseousState(string name) :State(name) {}; + void behavior(Water* p_water) const; + bool isMatch(int stateInfo) const; +}; + +class Water :public Context +{ +public: + Water(); + + int getTemperature(); + void setTemperature(int temperature); + void riseTemperature(int step); + void reduceTemperature(int step); + + void behavior(); + +}; diff --git a/inc/strategy.hpp b/inc/strategy.hpp new file mode 100644 index 0000000..d142484 --- /dev/null +++ b/inc/strategy.hpp @@ -0,0 +1,49 @@ +#pragma once +#include "common.hpp" + +class StrategyPerson +{ +public: + StrategyPerson(string name, int age, double weight, double height); + void showMyself(); + + string m_name; + int m_age; + double m_weight; + double m_height; +}; + +// Եij +class ICompare +{ +public: + virtual bool comparable(StrategyPerson* person1, StrategyPerson* person2) = 0; +}; + +// IJ +class CompareByAge :public ICompare +{ +public: + bool comparable(StrategyPerson* person1, StrategyPerson* person2); +}; + +class CompareByHeight :public ICompare +{ +public: + bool comparable(StrategyPerson* person1, StrategyPerson* person2); +}; + +class CompareByWeight :public ICompare +{ +public: + bool comparable(StrategyPerson* person1, StrategyPerson* person2); +}; + +class SortPerson +{ +public: + SortPerson(ICompare* pICompare); + void sort(vector& personList); +private: + ICompare* m_CompareStrategy; +}; diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..3a5500c --- /dev/null +++ b/main.cpp @@ -0,0 +1,22 @@ +#include "common.hpp" +#include "design_pattern.hpp" + + +int main() +{ + RunObserveMode(); + RunStateMode(); + RunDecorateMode(); + RunSingletonMode(); + RunPrototypeMode(); + RunChainOfResponsibilityMode(); + RunProxyMode(); + RunFacadeMode(); + RunIteratorMode(); + RunCombination(); + RunStrategyMode(); + RunSimpleFactoryMode(); + RunAbstractFactoryMode(); + return 0; + +} diff --git a/src/abstract_factory.cpp b/src/abstract_factory.cpp new file mode 100644 index 0000000..b87e9da --- /dev/null +++ b/src/abstract_factory.cpp @@ -0,0 +1,88 @@ +#include "abstract_factory.hpp" + +void Rectangle::draw() +{ + cout << "Inside Rectangle::draw() method." << endl; +} + +void Square::draw() +{ + cout << "Inside Square::draw() method." << endl; +} + +void Circle::draw() +{ + cout << "Inside Circle::draw() method." << endl; +} + +void Red::fill() +{ + cout << "Inside Red::fill() method." << endl; +} + +void Green::fill() +{ + cout << "Inside Green::fill() method." << endl; +} + +void Yellow::fill() +{ + cout << "Inside Yellow::fill() method." << endl; +} + +Shape* ShapeFactory::getShape(string shape) +{ + if (shape == "circle") + { + return new Circle(); + } + else if (shape == "rectangle") + { + return new Rectangle(); + } + else if (shape == "square") + { + return new Square(); + } + return nullptr; +} + +Color* ShapeFactory::getColor(string color) +{ + return nullptr; +} + +Shape* ColorFactory::getShape(string shape) +{ + return nullptr; +} + +Color* ColorFactory::getColor(string color) +{ + if (color == "red") + { + return new Red(); + } + else if (color == "green") + { + return new Green(); + } + else if (color == "yellow") + { + return new Yellow(); + } + return nullptr; +} + +AbstractFactory* FactoryProducer::getFactory(string choice) +{ + if (choice == "shape") + { + return new ShapeFactory(); + } + else if (choice == "color") + { + return new ColorFactory(); + } + return nullptr; +} diff --git a/src/chain_of_responsibility.cpp b/src/chain_of_responsibility.cpp new file mode 100644 index 0000000..f97fede --- /dev/null +++ b/src/chain_of_responsibility.cpp @@ -0,0 +1,96 @@ +#include "chain_of_responsibility.hpp" + +int PersonA::getDayoff() +{ + return m_Dayoff; +} + +string PersonA::getName() +{ + return m_Name; +} + +string PersonA::getReason() +{ + return m_Reason; +} + +void PersonA::setLeader(Manager* pLeader) +{ + m_pLeader = pLeader; +} + +void PersonA::Request() +{ + cout << m_Name << "" << m_Dayoff << "죬ɣ" << m_Reason << endl; + if (m_pLeader != nullptr) + { + m_pLeader->handleRequest(this); + } +} + +string Manager::getName() +{ + return m_Name; +} + +string Manager::getTitle() +{ + return m_Title; +} + +void Manager::setNextHander(Manager* p_NextHandler) +{ + m_pNextHandle = p_NextHandler; +} + +void Supervisor::handleRequest(PersonA* pPerson) +{ + if (pPerson->getDayoff() <= 2) + { + cout << "ͬ" << pPerson->getName() << "٣ǩˣ" << getName() << "(" << getTitle() << ")" << endl; + } + if (m_pNextHandle != nullptr) + { + m_pNextHandle->handleRequest(pPerson); + } +} + + +void DepartmentManager::handleRequest(PersonA* pPerson) +{ + if (pPerson->getDayoff() <= 5 && pPerson->getDayoff() > 2) + { + cout << "ͬ" << pPerson->getName() << "٣ǩˣ" << getName() << "(" << getTitle() << ")" << endl; + } + if (m_pNextHandle != nullptr) + { + m_pNextHandle->handleRequest(pPerson); + } +} + +void CEO::handleRequest(PersonA* pPerson) +{ + if (pPerson->getDayoff() > 5) + { + cout << "ͬ" << pPerson->getName() << "٣ǩˣ" << getName() << "(" << getTitle() << ")" << endl; + } + if (m_pNextHandle != nullptr) + { + m_pNextHandle->handleRequest(pPerson); + } +} + +void Administrator::handleRequest(PersonA* pPerson) +{ + + cout << pPerson->getName() << "ˣʵѱˣ" + << getName() << "(" << getTitle() << ")" << endl; + + cout << endl; + + if (m_pNextHandle != nullptr) + { + m_pNextHandle->handleRequest(pPerson); + } +} \ No newline at end of file diff --git a/src/combination.cpp b/src/combination.cpp new file mode 100644 index 0000000..15b0acd --- /dev/null +++ b/src/combination.cpp @@ -0,0 +1,122 @@ +#include "combination.hpp" + +bool ComputerComponent::isComposite() +{ + return false; +} + +void ComputerComponent::startup(string indent) +{ + cout << indent << m_name << " " << "׼ʼ" << endl; +} + +void ComputerComponent::shutdown(string indent) +{ + cout << indent << m_name << " " << "" << endl; +} + +void CPU::showInfo(string indent) +{ + cout << indent << "CPU" << indent << "Խи㡣" << endl; +} + +void MemoryCard::showInfo(string indent) +{ + cout << indent << "ڴ棺" << indent << "Իݣдٶȿ졣" << endl; +} + +void HardDisk::showInfo(string indent) +{ + cout << indent << "Ӳ̣" << indent << "ô洢ݣ洢" << endl; +} + +void GraphicsCard::showInfo(string indent) +{ + cout << indent << "Կ" << indent << "Ըټʹͼͼ" << endl; +} + +void Battery::showInfo(string indent) +{ + cout << indent << "Դ" << indent << "Գ硣" << endl; +} + +void Fan::showInfo(string indent) +{ + cout << indent << "ȣ" << indent << "CPUɢȡ" << endl; +} + +void Displayer::showInfo(string indent) +{ + cout << indent << "ʾ" << indent << "ݵʾ" << endl; +} + +void ComputerCompsite::showInfo(string indent) +{ + cout << m_name << "²ɣ" << endl; + vector::iterator iter; + for (iter = m_components.begin(); iter != m_components.end(); iter++) + { + (*iter)->showInfo(indent); + } +} + +bool ComputerCompsite::isComposite() +{ + return true; +} + +void ComputerCompsite::addComponent(ComputerComponent* component) +{ + m_components.push_back(component); +} + +void ComputerCompsite::removeComponent(ComputerComponent* component) +{ + vector::iterator iter = find(m_components.begin(), m_components.end(), component); + if (iter != m_components.end()) + { + m_components.erase(iter); + } +} + +void ComputerCompsite::startup(string indent) +{ + ComputerComponent::startup(indent); + indent += "\t"; + + vector::iterator iter; + for (iter = m_components.begin(); iter != m_components.end(); iter++) + { + (*iter)->startup(); + } +} + +void ComputerCompsite::shutdown(string indent) +{ + ComputerComponent::shutdown(indent); + indent += "\t"; + + vector::iterator iter; + for (iter = m_components.begin(); iter != m_components.end(); iter++) + { + (*iter)->shutdown(); + } +} + +void Mainboard::showInfo(string indent) +{ + cout << indent << "壺"; + ComputerCompsite::showInfo(indent); +} + +void ComputerCase::showInfo(string indent) +{ + cout << indent << "䣺"; + ComputerCompsite::showInfo(indent); +} + +void Computer::showInfo(string indent) +{ + cout << indent << "ԣ"; + ComputerCompsite::showInfo(indent); +} diff --git a/src/decorate.cpp b/src/decorate.cpp new file mode 100644 index 0000000..ee50fe8 --- /dev/null +++ b/src/decorate.cpp @@ -0,0 +1,74 @@ +#include "decorate.hpp" + +void Person::wear() +{ + cout << "װ" << endl; +} + +string Engineer::getSkill() +{ + return m_Skill; +} + +string Teacher::getTitle() +{ + return m_Title; +} + +void Teacher::wear() +{ + cout << "" << m_Name << m_Title << endl; + Person::wear(); +} + +void Engineer::wear() +{ + cout << "" << m_Skill << "ʦ " << m_Name << " " << endl; + Person::wear(); +} + +ClothingDecorator::~ClothingDecorator() +{ + if (m_pPerson != nullptr) + { + delete m_pPerson; + } +} + +void ClothingDecorator::wear() +{ + m_pPerson->wear(); + decorate(); +} + +void CasualPantDecorator::decorate() +{ + cout << "һɫп" << endl; +} + +void BeltDecorator::decorate() +{ + cout << "һɫͷúɫ" << endl; +} + +void LeatherShoesDecorator::decorate() +{ + cout << "һ˫ɫƤЬ" << endl; +} + +void KnittedSweaterDecorator::decorate() +{ + cout << "һϺɫ֯ë" << endl; +} + +void WhiteShirtDecorator::decorate() +{ + cout << "һɫ" << endl; +} + +void GlassesDecorator::decorate() +{ + cout << "һκڿ۾" << endl; +} + + diff --git a/src/design_pattern.cpp b/src/design_pattern.cpp new file mode 100644 index 0000000..4224c79 --- /dev/null +++ b/src/design_pattern.cpp @@ -0,0 +1,314 @@ +#include "design_pattern.hpp" + +void RunObserveMode(void) +{ + cout << "=============== Observer Mode =================" << endl; + + WaterHeater heater = WaterHeater(); + + WashingMode washingObser = WashingMode(); + DrinkingMode drinkingObser = DrinkingMode(); + + heater.RegisterObserver(&washingObser); + heater.RegisterObserver(&drinkingObser); + + heater.setTemperature(40); + heater.setTemperature(60); + heater.setTemperature(100); + + heater.UnRegisterObserver(&washingObser); + heater.setTemperature(60); + + cout << endl; +} + + +void RunStateMode(void) +{ + cout << "=============== State Mode =================" << endl; + + Water water = Water(); + water.behavior(); + + water.setTemperature(-4); + water.behavior(); + water.riseTemperature(18); + water.behavior(); + water.riseTemperature(90); + water.behavior(); + + cout << endl; + +} + +void RunDecorateMode() +{ + cout << "=============== Decorate Mode =================" << endl; + + Person* tony = new Engineer("Tony", "ͻ"); + + ClothingDecorator* clothes = new CasualPantDecorator(tony); + + clothes = new BeltDecorator(clothes); + clothes = new LeatherShoesDecorator(clothes); + clothes = new WhiteShirtDecorator(clothes); + clothes = new KnittedSweaterDecorator(clothes); + clothes = new GlassesDecorator(clothes); // ÿд洢ϸָ ʵ˵ݹ + + clothes->wear(); + + cout << endl; + + ClothingDecorator* decorateTeacher = new GlassesDecorator(new WhiteShirtDecorator( + new LeatherShoesDecorator(new Teacher("Jack", "")))); + + decorateTeacher->wear(); + + cout << endl; +} + + +void RunSingletonMode(void) +{ + cout << "=============== Singleton Mode =================" << endl; + + SingletonA* ptr1 = SingletonA::getInstance(); + SingletonA* ptr2 = SingletonA::getInstance(); + + cout << ptr1 << " " << ptr2 << endl; + + SingletonB* ptr3 = SingletonB::getInstance(); + SingletonB* ptr4 = SingletonB::getInstance(); + + cout << ptr3 << " " << ptr4 << endl; + cout << endl; +} + +void RunPrototypeMode(void) +{ + cout << "=============== Prototype Mode =================" << endl; + Prototype* ptr = new ConcretePrototype(); + + Prototype* copy_ptr = ptr->Clone(); + + delete ptr, copy_ptr; + cout << endl; + return; +} + +void RunChainOfResponsibilityMode(void) +{ + cout << "=============== Chain Of Responsibilty Mode =================" << endl; + Manager* directorLeader = new Supervisor("Eren", "ͻз"); + Manager* departmentManager = new DepartmentManager("Eric", "зܼ"); + Manager* ceo = new CEO("Helen", "Ļ˾CEO"); + Manager* administrator = new Administrator("Nina", "ܼ"); + + // + directorLeader->setNextHander(departmentManager); + departmentManager->setNextHander(ceo); + ceo->setNextHander(administrator); + + PersonA sunny("Sunny", 1, "μMDCC"); + sunny.setLeader(directorLeader); + sunny.Request(); + + PersonA tony("Tony", 5, "н"); + tony.setLeader(directorLeader); + tony.Request(); + + PersonA pony("Pony", 15, ""); + pony.setLeader(directorLeader); + pony.Request(); + + + delete directorLeader, departmentManager, ceo, administrator; + +} + +void RunProxyMode(void) +{ + cout << "=============== Proxy Mode =================" << endl; + + RealSubject realObj("RealSubject"); + ProxySubject proxyObj("ProxySubject", &realObj); + proxyObj.request(); + + cout << endl; +} + +void RunFacadeMode(void) +{ + cout << "=============== Facade Mode =================" << endl; + CompressionFacade facade; + + facade.compress("E;\\׼ļ\\еģʽ.md", "E;\\ѹļ\\еģʽ", "zip"); + facade.decompress("E;\\ѹļ\\еģʽ.zip", "E;\\׼ļ\\еģʽ.md"); + + facade.compress("E;\\׼ļ\\C++-ŵ.md", "E;\\ѹļ\\C++-ŵ", "rar"); + facade.decompress("E;\\ѹļ\\C++-ŵ.rar", "E;\\׼ļ\\C++-ŵ.md"); + + facade.compress("E;\\׼ļ\\ɸõṹ.md", "E;\\ѹļ\\ɸõṹ", "7z"); + facade.decompress("E;\\ѹļ\\ɸõṹ.7z", "E;\\׼ļ\\ɸõṹ.md"); + + cout << endl; +} + +void RunIteratorMode() +{ + cout << "=============== Iterator Mode =================" << endl; + NumeralSystem numeralSystem("Һ̨"); + + Customer lily("Lily"); + lily.Regist(&numeralSystem); + + Customer pony("Pony"); + pony.Regist(&numeralSystem); + + Customer nick("Nick"); + nick.Regist(&numeralSystem); + + Customer tony("Tony"); + tony.Regist(&numeralSystem); + + cout << endl; + + NumeralIterator iter = numeralSystem.getIterator(); // ĵ + while (iter.next()) + { + Customer* pCustomer = iter.current(); + cout << "һλˣ" << pCustomer->getNum() << "" << pCustomer->getName() << + ") 뵽" << pCustomer->getClinic() << "" << endl; + } + + cout << endl; +} + +void RunCombination(void) +{ + cout << "=============== Combination Mode =================" << endl; + + Mainboard* pmainBoard = new Mainboard("GIGABYTE Z170M M-ATX"); + pmainBoard->addComponent(new CPU("Inter Core i5-6600K")); + pmainBoard->addComponent(new MemoryCard("Kingston Fury DDR4")); + pmainBoard->addComponent(new HardDisk("Kingston V300")); + pmainBoard->addComponent(new GraphicsCard("Colorful iGame750")); + + ComputerCase* pcomputerCase = new ComputerCase("SAMA MATX"); + pcomputerCase->addComponent(pmainBoard); + pcomputerCase->addComponent(new Battery("Antec VP 450P")); + pcomputerCase->addComponent(new Fan("DEEPCOOL 120T")); + + Computer* pcomputer = new Computer("Tony DIY "); + pcomputer->addComponent(pcomputerCase); + pcomputer->addComponent(new Displayer("AOC LV243XIP")); + + pcomputer->showInfo(""); + cout << endl << "̣"; + pcomputer->startup(""); + cout << endl << "ػ̣"; + pcomputer->shutdown(""); + + cout << endl; + +} + +void RunStrategyMode(void) +{ + cout << "=============== Strategy Mode =================" << endl; + vector personList; + + personList.push_back(StrategyPerson("Tony", 2, 54.5, 0.82)); + personList.push_back(StrategyPerson("Jack", 31, 74.5, 1.80)); + personList.push_back(StrategyPerson("Nick", 54, 44.5, 1.59)); + personList.push_back(StrategyPerson("Eric", 23, 62.0, 1.78)); + personList.push_back(StrategyPerson("Helen",16, 45.7, 1.60)); + + SortPerson ageSort(new CompareByAge); + ageSort.sort(personList); + cout << "Ľ" << endl; + for (size_t i = 0; i < personList.size(); i++) + { + personList[i].showMyself(); + } + + SortPerson weightSort(new CompareByWeight); + weightSort.sort(personList); + cout << "ؽĽ" << endl; + for (size_t i = 0; i < personList.size(); i++) + { + personList[i].showMyself(); + } + cout << endl; +} + +void RunSimpleFactoryMode(void) +{ + cout << "=============== SimpleFactory Mode =================" << endl; + + PenFactory factory; + Pen* pLinePen = factory.CreatePen(PenTypeLine); + cout << "" << pLinePen->getName() << " ڴַ" << pLinePen << ", ͣ" << pLinePen->getType() << endl; + + pLinePen = factory.CreatePen(PenTypeRect); + cout << "" << pLinePen->getName() << " ڴַ" << pLinePen << ", ͣ" << pLinePen->getType() << endl; + + pLinePen = factory.CreatePen(PenTypeEllipse); + cout << "" << pLinePen->getName() << " ڴַ" << pLinePen << ", ͣ" << pLinePen->getType() << endl; + + pLinePen = factory.CreatePen(PenTypeRect); + cout << "" << pLinePen->getName() << " ڴַ" << pLinePen << ", ͣ" << pLinePen->getType() << endl; + + cout << endl; +} + +void RunAbstractFactoryMode(void) +{ + cout << "=============== AbstractFactory Mode =================" << endl; + AbstractFactory* pShapeFactory = FactoryProducer().getFactory("shape"); + + Shape* pShape1 = pShapeFactory->getShape("circle"); + + if (pShape1 != nullptr) + { + pShape1->draw(); + } + + Shape* pShape2 = pShapeFactory->getShape("square"); + + if (pShape2 != nullptr) + { + pShape2->draw(); + } + + Shape* pShape3 = pShapeFactory->getShape("rectangle"); + + if (pShape3 != nullptr) + { + pShape3->draw(); + } + + AbstractFactory* pColorFactory = FactoryProducer().getFactory("color"); + + Color* pColor1 = pColorFactory->getColor("red"); + + if (pColor1 != nullptr) + { + pColor1->fill(); + } + + Color* pColor2 = pColorFactory->getColor("green"); + + if (pColor2 != nullptr) + { + pColor2->fill(); + } + + Color* pColor3 = pColorFactory->getColor("yellow"); + + if (pColor3 != nullptr) + { + pColor3->fill(); + } + cout << endl; +} diff --git a/src/facade.cpp b/src/facade.cpp new file mode 100644 index 0000000..5806578 --- /dev/null +++ b/src/facade.cpp @@ -0,0 +1,103 @@ +#include "facade.hpp" + +void ZIPModel::compress(string srcFilePath, string dstFilePath) +{ + cout << "ZIPģڽС" << srcFilePath << "ѹ" << endl; + cout << "ļѹɹѱ" << dstFilePath << "" << endl; +} + +void ZIPModel::decompress(string srcFilePath, string dstFilePath) +{ + cout << "ZIPģڽС" << srcFilePath << "Ľѹ" << endl; + cout << "ļѹɹѱ" << dstFilePath << "" << endl; +} + +void ZModel::compress(string srcFilePath, string dstFilePath) +{ + cout << "7ZģڽС" << srcFilePath << "ѹ" << endl; + cout << "ļѹɹѱ" << dstFilePath << "" << endl; +} + +void ZModel::decompress(string srcFilePath, string dstFilePath) +{ + cout << "7ZģڽС" << srcFilePath << "Ľѹ" << endl; + cout << "ļѹɹѱ" << dstFilePath << "" << endl; +} + +void RARModel::compress(string srcFilePath, string dstFilePath) +{ + cout << "RARģڽС" << srcFilePath << "ѹ" << endl; + cout << "ļѹɹѱ" << dstFilePath << "" << endl; +} + +void RARModel::decompress(string srcFilePath, string dstFilePath) +{ + cout << "RARģڽС" << srcFilePath << "Ľѹ" << endl; + cout << "ļѹɹѱ" << dstFilePath << "" << endl; +} + +CompressionFacade::CompressionFacade(ZIPModel* pZipModel, RARModel* pRarModel, ZModel* pZModel) +{ + m_pRarModel = pRarModel; + m_pZModel = pZModel; + m_pZipModel = pZipModel; +} + +CompressionFacade::~CompressionFacade() +{ + if (m_pRarModel != nullptr) + { + delete m_pRarModel; + } + + if (m_pZModel != nullptr) + { + delete m_pZModel; + } + + if (m_pZipModel != nullptr) + { + delete m_pZipModel; + } +} + +void CompressionFacade::compress(string srcFilePath, string dstFilePath, string type) +{ + string fullName = dstFilePath + '.' + type; + if (type == "zip") + { + m_pZipModel->compress(srcFilePath, fullName); + } + else if (type == "rar") + { + m_pRarModel->compress(srcFilePath, fullName); + } + else if (type == "7z") + { + m_pZModel->compress(srcFilePath, fullName); + } + return; + +} + +void CompressionFacade::decompress(string srcFilePath, string dstFilePath) +{ + string::iterator iter = find(srcFilePath.begin(), srcFilePath.end(), '.'); + string baseName(srcFilePath.begin(), iter); + + string extName(iter, srcFilePath.end()); + + if (extName == "zip") + { + m_pZipModel->decompress(srcFilePath, baseName); + } + else if (extName == "rar") + { + m_pRarModel->decompress(srcFilePath, baseName); + } + else if (extName == "7z") + { + m_pZModel->decompress(srcFilePath, baseName); + } + return; +} diff --git a/src/iteration.cpp b/src/iteration.cpp new file mode 100644 index 0000000..cdf1cf6 --- /dev/null +++ b/src/iteration.cpp @@ -0,0 +1,64 @@ +#include "iterator.hpp" + +vector NumeralSystem::m_clinics = vector{ "1", "2", "3" };; +string Customer::getName() +{ + return m_name; +} + +void Customer::Regist(NumeralSystem* system) +{ + system->pushCustomer(this); +} + +void Customer::setNum(int num) +{ + m_num = num; +} + +int Customer::getNum() +{ + return m_num; +} + +void Customer::setClinic(string clinic) +{ + m_clinics = clinic; +} + +string Customer::getClinic() +{ + return m_clinics; +} + +bool NumeralIterator::next() +{ + if (m_curIdx < (int)m_data.size() - 1) + { + m_curIdx++; + return true; + } + return false; +} + +Customer* NumeralIterator::current() +{ + return m_curIdx < m_data.size() ? m_data[m_curIdx] : NULL; +} + +void NumeralSystem::pushCustomer(Customer* pCustomer) +{ + pCustomer->setNum(m_curNum + 1); + string click = NumeralSystem::m_clinics[m_curNum % NumeralSystem::m_clinics.size()]; + pCustomer->setClinic(click); + + m_curNum++; + m_pCustomers.push_back(pCustomer); + cout << pCustomer->getName() << " ã" << m_name << "ɹҺţţ" << + pCustomer->getNum() << "ĵȴ" << endl; +} + +NumeralIterator NumeralSystem::getIterator() +{ + return NumeralIterator(m_pCustomers); +} diff --git a/src/observe.cpp b/src/observe.cpp new file mode 100644 index 0000000..93d46f2 --- /dev/null +++ b/src/observe.cpp @@ -0,0 +1,63 @@ +#include "observe.hpp" + +int WaterHeater::getTempetature() +{ + return m_temperature; +} + +void WaterHeater::setTemperature(int temperature) +{ + m_temperature = temperature; + cout << "ǰˮ " << temperature << " " << endl; + HandleObserver(); + return; +} + +bool WaterHeater::RegisterObserver(Observer* inObserver) +{ + vector::iterator iter = find(m_Observers.begin(), m_Observers.end(), inObserver); + if (iter == m_Observers.end()) + { + m_Observers.push_back(inObserver); + return true; + } + return false; +} + +bool WaterHeater::UnRegisterObserver(Observer* inObserver) +{ + vector::iterator iter = find(m_Observers.begin(), m_Observers.end(), inObserver); + if (iter != m_Observers.end()) + { + m_Observers.erase(iter); + return true; + } + return false; +} + +void WaterHeater::HandleObserver() +{ + for (vector::iterator iter = m_Observers.begin(); iter != m_Observers.end(); iter++) + { + (*iter)->Update(this); + } + return; +} + +void WashingMode::Update(WaterHeater* waterHeater) const +{ + if (waterHeater->getTempetature() >= 50 && waterHeater->getTempetature() < 70) + { + cout << "ˮպã¶ãϴˡ" << endl; + } + return; +} + +void DrinkingMode::Update(WaterHeater* waterHeater) const +{ + if (waterHeater->getTempetature() >= 100) + { + cout << "ˮտˡ" << endl; + } + return; +} diff --git a/src/prototype.cpp b/src/prototype.cpp new file mode 100644 index 0000000..055040d --- /dev/null +++ b/src/prototype.cpp @@ -0,0 +1,12 @@ +#include "prototype.hpp" + +ConcretePrototype::ConcretePrototype(const ConcretePrototype& c) +{ + cout << "ConcretePrototype copy construct!" << endl; +} + +Prototype* ConcretePrototype::Clone() +{ + return new ConcretePrototype(*this); +} + diff --git a/src/proxy.cpp b/src/proxy.cpp new file mode 100644 index 0000000..4d97bba --- /dev/null +++ b/src/proxy.cpp @@ -0,0 +1,32 @@ +#include "proxy.hpp" + + +string Subject::getName() +{ + return m_Name; +} + +void RealSubject::request() +{ + cout << "RealSubject to do something" << endl; +} + +void ProxySubject::request() +{ + preRequest(); + if (m_pSubject != nullptr) + { + m_pSubject->request(); + } + afterRequest(); +} + +void ProxySubject::preRequest() +{ + cout << "preRequest" << endl; +} + +void ProxySubject::afterRequest() +{ + cout << "afterRequest" << endl; +} diff --git a/src/simple_factory.cpp b/src/simple_factory.cpp new file mode 100644 index 0000000..74e0ac7 --- /dev/null +++ b/src/simple_factory.cpp @@ -0,0 +1,50 @@ +#include "simple_factory.hpp" + +Pen::Pen(string name) +{ + m_name = name; +} + +string Pen::getName() +{ + return m_name; +} + +PenType LinePen::getType() +{ + return PenTypeLine; +} + +PenType RectanglePen::getType() +{ + return PenTypeRect; +} + +PenType EllipsePen::getType() +{ + return PenTypeEllipse; +} + +Pen* PenFactory::CreatePen(PenType pentype) +{ + if (m_PenProduct.find(pentype) == m_PenProduct.end()) + { + if (pentype == PenTypeLine) + { + m_PenProduct[pentype] = new LinePen("ֱ߻"); + } + else if(pentype == PenTypeRect) + { + m_PenProduct[pentype] = new RectanglePen("λ"); + } + else if (pentype == PenTypeEllipse) + { + m_PenProduct[pentype] = new EllipsePen("Բ"); + } + else + { + return nullptr; + } + } + return m_PenProduct[pentype]; +} diff --git a/src/singleton.cpp b/src/singleton.cpp new file mode 100644 index 0000000..2ebf983 --- /dev/null +++ b/src/singleton.cpp @@ -0,0 +1,18 @@ +#include "singleton.hpp" + +SingletonA* SingletonA::m_pInstance = nullptr; + +SingletonA* SingletonA::getInstance() +{ + if (m_pInstance == nullptr) + { + m_pInstance = new SingletonA(); + } + return m_pInstance; +} + +SingletonB* SingletonB::getInstance() +{ + static SingletonB Instance; + return &Instance; +} diff --git a/src/state.cpp b/src/state.cpp new file mode 100644 index 0000000..5f7e84d --- /dev/null +++ b/src/state.cpp @@ -0,0 +1,140 @@ +#include "state.hpp" + +void SolidState::behavior(Water* p_water) const +{ + cout << "ǰ״̬Ϊ̬¶Ϊ" << p_water->getTemperature() << "" << endl; +} + +bool SolidState::isMatch(int stateInfo) const +{ + return stateInfo <= 0; +} + +void Liquidtate::behavior(Water* p_water) const +{ + cout << "ǰ״̬ΪҺ̬¶Ϊ" << p_water->getTemperature() << "" << endl; +} + +bool Liquidtate::isMatch(int stateInfo) const +{ + return stateInfo > 0 && stateInfo < 100; +} + +void GaseousState::behavior(Water* p_water) const +{ + cout << "ǰ״̬Ϊ̬¶Ϊ" << p_water->getTemperature() << "" << endl; +} + +bool GaseousState::isMatch(int stateInfo) const +{ + return stateInfo >= 100; +} + +Water::Water() +{ + addState(new SolidState("̬")); + addState(new Liquidtate("Һ̬")); + addState(new GaseousState("̬")); + + setTemperature(25); +} + +int Water::getTemperature() +{ + return getStateInfo(); +} + +void Water::setTemperature(int temperature) +{ + setStateInfo(temperature); +} + +void Water::riseTemperature(int step) +{ + setTemperature(getTemperature() + step); +} + +void Water::reduceTemperature(int step) +{ + setTemperature(getTemperature() - step); +} + +void Water::behavior() +{ + State* p_state = getState(); + p_state->behavior(this); +} + +string State::getName() +{ + return m_name; +} + +Context::Context() +{ + m_stateInfo = 0; + p_curState = nullptr; +} + +Context::~Context() +{ + vector::iterator iter = p_states.begin(); + for (; iter != p_states.end(); iter++) + { + delete (*iter); // ͷڴ + } + p_states.clear(); +} + +void Context::addState(State* state) +{ + vector::iterator iter = find(p_states.begin(), p_states.end(), state); + if (iter == p_states.end()) + { + p_states.push_back(state); + } +} + +bool Context::changeState(State* state) +{ + vector::iterator iter = find(p_states.begin(), p_states.end(), state); + if (iter == p_states.end()) + { + return false; + } + + if (p_curState == nullptr) + { + cout << "ʼΪ " << state->getName() << endl; + } + else + { + cout << " " << p_curState->getName() << " Ϊ " << state->getName() << endl; + } + p_curState = state; + return true; +} + +State* Context::getState() +{ + return p_curState; +} + +void Context::setStateInfo(int stateInfo) +{ + m_stateInfo = stateInfo; + for (vector::iterator iter = p_states.begin(); iter != p_states.end(); iter++) + { + if ((*iter)->isMatch(stateInfo)) + { + changeState((*iter)); + break; + } + } + +} + +int Context::getStateInfo() +{ + return m_stateInfo; +} diff --git a/src/strategy.cpp b/src/strategy.cpp new file mode 100644 index 0000000..e43ebdd --- /dev/null +++ b/src/strategy.cpp @@ -0,0 +1,47 @@ +#include "strategy.hpp" + +SortPerson::SortPerson(ICompare* pICompare) +{ + m_CompareStrategy = pICompare; +} + +void SortPerson::sort(vector& personList) +{ + for (size_t i = 0; i < personList.size() - 1; i++) // Bubble sort + { + for (size_t j = i + 1; j < personList.size(); j++) + { + if (m_CompareStrategy->comparable(&personList[i], &personList[j])) + { + StrategyPerson temp = personList[i]; + personList[i] = personList[j]; + personList[j] = temp; + } + } + } +} + +bool CompareByWeight::comparable(StrategyPerson* person1, StrategyPerson* person2) +{ + return person1->m_weight < person2->m_weight; +} + +bool CompareByHeight::comparable(StrategyPerson* person1, StrategyPerson* person2) +{ + return person1->m_height < person2->m_height; +} + +bool CompareByAge::comparable(StrategyPerson* person1, StrategyPerson* person2) +{ + return person1->m_age < person2->m_age; +} + +StrategyPerson::StrategyPerson(string name, int age, double weight, double height) +{ + m_name = name, m_age = age, m_weight = weight, m_height = height; +} + +void StrategyPerson::showMyself() +{ + cout << m_name << " 䣺" << m_age << ", أ" << m_weight << "kg, ߣ" << m_height << "m" << endl; +}