initialize repository of design pattern template

This commit is contained in:
LU
2025-08-09 08:41:14 +08:00
commit 1727e31b9d
32 changed files with 2149 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
build
+20
View File
@@ -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})
+79
View File
@@ -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);
};
+74
View File
@@ -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);
};
+102
View File
@@ -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<ComputerComponent*> 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);
};
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <iterator>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <memory>
#include <queue>
#include <string>
using namespace std;
+96
View File
@@ -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();
};
+29
View File
@@ -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);
+37
View File
@@ -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;
};
+152
View File
@@ -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<Customer*> data, int curIdx = -1) :m_data(data), m_curIdx(curIdx) {};
bool next();
Customer* current();
private:
vector<Customer*> m_data;
int m_curIdx;
};
class NumeralSystem
{
public:
static vector<string> m_clinics;
NumeralSystem(string name) : m_name(name)
{
m_curNum = 0;
}
void pushCustomer(Customer* pCustomer);
NumeralIterator getIterator();
private:
vector<Customer*> 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<string> m_vecItems;
Iterator* m_pIterator;
};
+39
View File
@@ -0,0 +1,39 @@
#pragma once
#include "common.hpp"
class WaterHeater;
class Observer // 观察者的抽象基类
{
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<Observer*> m_Observers;
};
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include "common.hpp"
class Prototype // C++ 本身的拷贝函数为浅拷贝,原型模式为深拷贝
{
public:
Prototype() {}
~Prototype() {}
virtual Prototype* Clone() = 0;
};
class ConcretePrototype :public Prototype
{
public:
ConcretePrototype() {}
~ConcretePrototype() {}
virtual Prototype* Clone();
private:
ConcretePrototype(const ConcretePrototype&); //
};
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include "common.hpp"
class Subject // 主题的抽象基类
{
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;
};
+50
View File
@@ -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<PenType, Pen*> m_PenProduct;
};
+29
View File
@@ -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();
};
+74
View File
@@ -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<State*> 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();
};
+49
View File
@@ -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;
};
// ¾ßÌåµÄ²ßÂÔ
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<StrategyPerson>& personList);
private:
ICompare* m_CompareStrategy;
};
+22
View File
@@ -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;
}
+88
View File
@@ -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;
}
+96
View File
@@ -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);
}
}
+122
View File
@@ -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<ComputerComponent*>::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<ComputerComponent*>::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<ComputerComponent*>::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<ComputerComponent*>::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);
}
+74
View File
@@ -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;
}
+314
View File
@@ -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<StrategyPerson> 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;
}
+103
View File
@@ -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;
}
+64
View File
@@ -0,0 +1,64 @@
#include "iterator.hpp"
vector<string> NumeralSystem::m_clinics = vector<string>{ "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);
}
+63
View File
@@ -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<Observer*>::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<Observer*>::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<Observer*>::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;
}
+12
View File
@@ -0,0 +1,12 @@
#include "prototype.hpp"
ConcretePrototype::ConcretePrototype(const ConcretePrototype& c)
{
cout << "ConcretePrototype copy construct!" << endl;
}
Prototype* ConcretePrototype::Clone()
{
return new ConcretePrototype(*this);
}
+32
View File
@@ -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;
}
+50
View File
@@ -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];
}
+18
View File
@@ -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;
}
+140
View File
@@ -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<State*>::iterator iter = p_states.begin();
for (; iter != p_states.end(); iter++)
{
delete (*iter); // 释放内存
}
p_states.clear();
}
void Context::addState(State* state)
{
vector<State*>::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<State*>::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<State*>::iterator iter = p_states.begin(); iter != p_states.end(); iter++)
{
if ((*iter)->isMatch(stateInfo))
{
changeState((*iter));
break;
}
}
}
int Context::getStateInfo()
{
return m_stateInfo;
}
+47
View File
@@ -0,0 +1,47 @@
#include "strategy.hpp"
SortPerson::SortPerson(ICompare* pICompare)
{
m_CompareStrategy = pICompare;
}
void SortPerson::sort(vector<StrategyPerson>& 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;
}