C++设计模式提供了一些常见的问题和解决方案,帮助我们写出更清晰、更高效、更容易维护的代码。
1.单例模式:就像整形诊所里有一个特别的规定,全世界只能有一个人拥有某款独一无二的鼻子,其他人都不能复制。
(确保一个类只有一个实例,并提供一个全局访问点。)
class Singleton {
private:
static Singleton* instance;
Singleton() {} // 私有构造函数
public:
static Singleton* getInstance() {
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
2.工厂方法模式:就像你告诉整形医生你想要什么样的眼睛,医生会根据你的需求定制,但具体是哪个医生操作,你不需要知道。(定义创建对象的接口,但让子类决定实例化哪一个类。)
// 产品基类
class Product {
public:
virtual ~Product() {}
virtual void Use() = 0;
};
// 具体产品A
class ConcreteProductA : public Product {
public:
void Use() override {
std::cout << "Using A" << std::endl;
}
};
// 具体产品B
class ConcreteProductB : public Product {
public:
void Use() override {
std::cout << "Using B" << std::endl;
}
};
// 工厂基类
class Creator {
public:
virtual ~Creator() {}
virtual Product* FactoryMethod() = 0;
};
// 具体工厂A
class ConcreteCreatorA : public Creator {
public:
Product* FactoryMethod() override {
return new ConcreteProductA();
}
};
// 具体工厂B
class ConcreteCreatorB : public Creator {
public:
Product* FactoryMethod() override {
return new ConcreteProductB();
}
};
3.抽象工厂模式:就像一个大型的整形医院,可以提供一整套整形服务,包括眼睛、鼻子、下巴等,你只需要告诉医院你想要一整套整形方案,医院会按照一套标准给你安排。(提供一个创建一系列相关或相互依赖对象的接口,而不需要指定它们具体的类。)
// 产品族A
class AbstractProductA {
public:
virtual ~AbstractProductA() {}
virtual void UsefulFunctionA() = 0;
};
// 产品族B
class AbstractProductB {
public:
virtual ~AbstractProductB() {}
virtual void UsefulFunctionB() = 0;
};
// 具体产品A1
class ConcreteProductA1 : public AbstractProductA {
public:
void UsefulFunctionA() override {
std::cout << "The result of product A1." << std::endl;
}
};
// 具体产品B1
class ConcreteProductB1 : public AbstractProductB {
public:
void UsefulFunctionB() override {
std::cout << "The result of product B1." << std::endl;
}
};
// 抽象工厂
class AbstractFactory {
public:
virtual ~AbstractFactory() {}
virtual AbstractProductA* CreateProductA() = 0;
virtual AbstractProductB* CreateProductB() = 0;
};
// 具体工厂
class ConcreteFactory : public AbstractFactory {
public:
AbstractProductA* CreateProductA() override {
return new ConcreteProductA1();
}
AbstractProductB* CreateProductB() override {
return new ConcreteProductB1();
}
};
4.建造者模式:就像整形手术中的逐步调整,你可以按照不同的步骤和顺序来调整你的面部特征,以达到最终的效果。(将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。)
// 产品类
class Product {
public:
void Show() {
std::cout << "Product has been built." << std::endl;
}
};
// 建造者接口
class Builder {
public:
virtual ~Builder() {}
virtual void BuildPartA() = 0;
virtual void BuildPartB() = 0;
virtual Product GetResult() = 0;
};
// 具体建造者
class ConcreteBuilder : public Builder {
private:
Product product;
public:
void BuildPartA() override {
std::cout << "Building PartA" << std::endl;
}
void BuildPartB() override {
std::cout << "Building PartB" << std::endl;
}
Product GetResult() override {
return product;
}
};
// 指挥者
class Director {
public:
void Construct(Builder* builder) {
builder->BuildPartA();
builder->BuildPartB();
}
};
5.原型模式:就像整形手术中的克隆技术,你可以复制一个已经整形成功的人的脸,而不是从头开始设计。(通过拷贝现有的实例创建新的实例,而不是通过新建一个实例。)
#include <iostream>
#include <memory>
class Prototype {
public:
virtual ~Prototype() {}
virtual Prototype* Clone() const = 0;
};
class ConcretePrototype : public Prototype {
private:
int field;
public:
ConcretePrototype(int field) : field(field) {}
Prototype* Clone() const override {
return new ConcretePrototype(*this);
}
void Operation() {
std::cout << "Prototype " << field << std::endl;
}
};
int main() {
std::unique_ptr<Prototype> prototype(new ConcretePrototype(100));
std::unique_ptr<Prototype> clone = prototype->Clone();
clone->Operation();
return 0;
}
6.适配器模式:就像整形手术中的面部调整,让你的面部特征能够适应不同的美学标准。
(允许不兼容的接口协同工作。)
// 目标接口
class Target {
public:
virtual void Request() = 0;
};
// 客户端需要的类
class Client {
public:
void UseTarget(Target* target) {
target->Request();
}
};
// 被适配的类
class Adaptee {
public:
void SpecificRequest() {
std::cout << "Specific Request" << std::endl;
}
};
// 适配器类
class Adapter : public Target {
private:
Adaptee* adaptee;
public:
Adapter(Adaptee* adaptee) : adaptee(adaptee) {}
void Request() override {
adaptee->SpecificRequest();
}
};
- 装饰器模式:就像整形手术中的额外装饰,比如纹眉、纹眼线,你可以在不改变面部结构的情况下,增加一些新的美学特征。(动态地给一个对象添加一些额外的职责。)
#include <iostream>
#include <memory>
// 组件接口
class Component {
public:
virtual ~Component() {}
virtual void Operation() = 0;
};
// 具体组件
class ConcreteComponent : public Component {
public:
void Operation() override {
std::cout << "ConcreteComponent" << std::endl;
}
};
// 装饰器抽象类
class Decorator : public Component {
protected:
Component* component;
public:
Decorator(Component* component) : component(component) {}
void Operation() override {
component->Operation();
}
};
// 具体装饰器A
class ConcreteDecoratorA : public Decorator {
public:
ConcreteDecoratorA(Component* component) : Decorator(component) {}
void Operation() override {
Decorator::Operation();
AddBehavior();
}
private:
void AddBehavior() {
std::cout << "ConcreteDecoratorA" << std::endl;
}
};
// 具体装饰器B
class ConcreteDecoratorB : public Decorator {
public:
ConcreteDecoratorB(Component* component) : Decorator(component) {}
void Operation() override {
Decorator::Operation();
AddBehavior();
}
private:
void AddBehavior() {
std::cout << "ConcreteDecoratorB" << std::endl;
}
};
8.外观模式:就像整形医院的前台,你只需要告诉前台你想要什么样的整形效果,前台会帮你安排所有的手术流程。
(为系统中的一组接口提供一个统一的高层接口。)
// 子系统类A
class SubSystemA {
public:
void Operation() {
std::cout << "SubSystemA operation" << std::endl;
}
};
// 子系统类B
class SubSystemB {
public:
void Operation() {
std::cout << "SubSystemB operation" << std::endl;
}
};
// 外观类
class Facade {
private:
SubSystemA* subSystemA;
SubSystemB* subSystemB;
public:
Facade() {
subSystemA = new SubSystemA();
subSystemB = new SubSystemB();
}
~Facade() {
delete subSystemA;
delete subSystemB;
}
void Operation() {
subSystemA->Operation();
subSystemB->Operation();
}
};
9.享元模式:就像整形手术中的共享资源,比如共享同一型号的假体,通过共享来减少成本和资源浪费。(通过共享来高效地支持大量的细粒度对象。)
#include <iostream>
#include <unordered_map>
#include <memory>
class Flyweight {
public:
virtual void Operation(int extrinsicState) = 0;
};
class ConcreteFlyweight : public Flyweight {
private:
std::string intrinsicState;
public:
ConcreteFlyweight(const std::string& intrinsicState) : intrinsicState(intrinsicState) {}
void Operation(int extrinsicState) override {
std::cout << "ConcreteFlyweight: " << intrinsicState << ", " << extrinsicState << std::endl;
}
};
class FlyweightFactory {
private:
std::unordered_map<std::string, std::shared_ptr<Flyweight>> flyweights;
public:
std::shared_ptr<Flyweight> GetFlyweight(const std::string& key) {
if (flyweights.find(key) == flyweights.end()) {
flyweights[key] = std::make_shared<ConcreteFlyweight>(key);
}
return flyweights[key];
}
};
int main() {
FlyweightFactory factory;
std::shared_ptr<Flyweight> fw1 = factory.GetFlyweight("Item1");
std::shared_ptr<Flyweight> fw2 = factory.GetFlyweight("Item1");
fw1->Operation(10);
fw2->Operation(20);
return 0;
}
10.代理模式就像整形手术中的代理,帮你处理所有的手术安排和后续服务,你只需要和代理沟通。(为其他对象提供一种代理以控制对这个对象的访问。)
#include <iostream>
// 代理类
class Proxy {
private:
std::unique_ptr<RealSubject> realSubject;
public:
Proxy() {}
void Request() {
if (realSubject == nullptr) {
realSubject = std::make_unique<RealSubject>();
}
realSubject->Request();
}
};
// 真实主题类
class RealSubject {
public:
void Request() {
std::cout << "RealSubject: Handling Request." << std::endl;
}
11.命令模式:就像整形手术中的指令系统,你可以发出指令,比如“我想要这样的鼻子”,然后系统会帮你实现。(将请求封装为一个对象,从而可以使用不同的请求、队列或日志请求。)
#include <iostream>
#include <memory>
#include <vector>
// 命令接口
class Command {
public:
virtual ~Command() {}
virtual void Execute() = 0;
};
// 具体命令
class ConcreteCommand : public Command {
private:
std::unique_ptr<Receiver> receiver;
public:
ConcreteCommand(std::unique_ptr<Receiver> receiver) : receiver(std::move(receiver)) {}
void Execute() override {
receiver->Action();
}
};
// 接收者
class Receiver {
public:
void Action() {
std::cout << "Receiver action." << std::endl;
}
};
// 调用者
class Invoker {
private:
std::vector<std::unique_ptr<Command>> commands;
public:
void StoreAndExecute(Command* cmd) {
commands.push_back(std::unique_ptr<Command>(cmd));
cmd->Execute();
}
};
int main() {
std::unique_ptr<Receiver> receiver = std::make_unique<Receiver>();
std::unique_ptr<Command> command = std::make_unique<ConcreteCommand>(std::move(receiver));
std::unique_ptr<Invoker> invoker = std::make_unique<Invoker>();
invoker->StoreAndExecute(command.get());
return 0;
}
12.观察者模式:就像整形手术后的跟踪服务,一旦有新的整形技术或者你的恢复情况有更新,医院会及时通知你。(当对象间存在一对多关系时,则使用观察者模式。)
#include <iostream>
#include <list>
#include <algorithm>
// 观察者接口
class Observer {
public:
virtual ~Observer() {}
virtual void Update(int state) = 0;
};
// 具体观察者
class ConcreteObserver : public Observer {
public:
void Update(int state) override {
std::cout << "ConcreteObserver: " << state << std::endl;
}
};
// 主题接口
class Subject {
public:
virtual ~Subject() {}
virtual void Attach(Observer* observer) = 0;
virtual void Detach(Observer* observer) = 0;
virtual void Notify() = 0;
};
// 具体主题
class ConcreteSubject : public Subject {
private:
std::list<Observer*> observers;
int state;
public:
void Attach(Observer* observer) override {
observers.push_back(observer);
}
void Detach(Observer* observer) override {
observers.remove(observer);
}
void Notify() override {
for (Observer* observer : observers) {
observer->Update(state);
}
}
void ChangeState(int newState) {
state = newState;
Notify();
}
};
int main() {
std::unique_ptr<ConcreteSubject> subject = std::make_unique<ConcreteSubject>();
std::unique_ptr<ConcreteObserver> observer = std::make_unique<ConcreteObserver>();
subject->Attach(observer.get());
subject->ChangeState(1);
subject->Detach(observer.get());
subject->ChangeState(2);
return 0;
}
- 策略模式:就像整形手术中的不同整形方案,你可以根据不同的需求选择不同的整形策略,随时可以更换。(定义一系列算法,把它们一个个封装起来,并使它们可以相互替换。)
#include <iostream> #include <memory> // 策略接口 class Strategy { public: virtual ~Strategy() {} virtual void AlgorithmInterface() = 0; }; // 具体策略A class ConcreteStrategyA : public Strategy { public: void AlgorithmInterface() override { std::cout << "ConcreteStrategyA" << std::endl; } }; // 具体策略B class ConcreteStrategyB : public Strategy { public: void AlgorithmInterface() override { std::cout << "ConcreteStrategyB" << std::endl; } }; // 上下文 class Context { private: std::unique_ptr<Strategy> strategy; public: void SetStrategy(std::unique_ptr<Strategy> strategy) { this->strategy = std::move(strategy); } void ExecuteStrategy() { strategy->AlgorithmInterface(); } }; int main() { std::unique_ptr<Context> context = std::make_unique<Context>(); context->SetStrategy(std::make_unique<ConcreteStrategyA>()); context->ExecuteStrategy(); context->SetStrategy(std::make_unique<ConcreteStrategyB>()); context->ExecuteStrategy(); return 0; }
模板方法模式:就像整形手术中的手术流程模板,定义了手术的基本步骤,但具体每一步怎么做,可以根据每个人的情况来调整。(在方法中定义算法的骨架,而将一些步骤延迟到子类中实现。)
#include <iostream>
// 抽象类
class AbstractClass {
public:
virtual ~AbstractClass() {}
void TemplateMethod() {
PrimitiveOperation1();
PrimitiveOperation2();
ConcreteOperation();
}
virtual void ConcreteOperation() = 0;
protected:
void PrimitiveOperation1() {
std::cout << "AbstractClass: PrimitiveOperation1" << std::endl;
}
void PrimitiveOperation2() {
std::cout << "AbstractClass: PrimitiveOperation2" << std::endl;
}
};
// 具体实现A
class ConcreteClassA : public AbstractClass {
public:
void ConcreteOperation() override {
std::cout << "ConcreteClassA: ConcreteOperation" << std::endl;
}
};
// 具体实现B
class ConcreteClassB : public AbstractClass {
public:
void ConcreteOperation() override {
std::cout << "ConcreteClassB: ConcreteOperation" << std::endl;
}
};
int main() {
std::unique_ptr<AbstractClass> objectA = std::make_unique<ConcreteClassA>();
objectA->TemplateMethod();
std::unique_ptr<AbstractClass> objectB = std::make_unique<ConcreteClassB>();
objectB->TemplateMethod();
return 0;
}
- 访问者模式:就像整形手术后的回访,医生会根据不同的恢复情况来提供不同的护理建议。(允许一个或者多个操作应用到一组对象上,解耦操作和对象本身。)
#include <iostream>
#include <vector>
#include <memory>
// 元素接口
class Element {
public:
virtual ~Element() {}
virtual void Accept(class Visitor* visitor) = 0;
};
// 具体元素A
class ConcreteElementA : public Element {
public:
void Accept(Visitor* visitor) override {
visitor->Visit(this);
}
void OperationA() {
std::cout << "ConcreteElementA" << std::endl;
}
};
// 具体元素B
class ConcreteElementB : public Element {
public:
void Accept(Visitor* visitor) override {
visitor->Visit(this);
}
void OperationB() {
std::cout << "ConcreteElementB" << std::endl;
}
};
// 访问者接口
class Visitor {
public:
virtual ~Visitor() {}
virtual void Visit(ConcreteElementA* element) = 0;
virtual void Visit(ConcreteElementB* element) = 0;
};
// 具体访问者
class ConcreteVisitor : public Visitor {
public:
void Visit(ConcreteElementA* element) override {
element->OperationA();
}
void Visit(ConcreteElementB* element) override {
element->OperationB();
}
};
int main() {
std::vector<std::unique_ptr<Element>> elements;
elements.push_back(std::make_unique<ConcreteElementA>());
elements.push_back(std::make_unique<ConcreteElementB>());
std::unique_ptr<Visitor> visitor = std::make_unique<ConcreteVisitor>();
for (auto& element : elements) {
element->Accept(visitor.get());
}
return 0;
}
标签:std,unique,void,C++,class,virtual,设计模式,public From: https://blog.csdn.net/empwzj/article/details/142461215