【C++】八大常见的设计模式

SuhyOvO 2024-10-23 09:35:02 阅读 59

文章目录

八大常见的设计模式1. 单例模式饿汉式单例模式懒汉式单例模式

2. 工厂设计模式普通工厂模式多个工厂方法模式静态工厂方法模式抽象工厂模式

3. 建造者模式4. 适配器设计模式类适配器模式对象适配器模式

接口的适配器模式

5、Decorator Pattern(装饰模式)6、Strategy Pattern(策略模式)7、Proxy Pattern(代理模式)8、Template Method Pattern(模板方法模式)


八大常见的设计模式

设计模式是一种编写代码的方式,旨在解决常见的软件设计问题。这些模式提供了代码重用和易于维护的解决方案。本文将讲解几种常见的设计模式,并使用C++编写相应的代码示例。

1. 单例模式

单例模式确保一个类只有一个实例,并提供一个全局访问点。

饿汉式单例模式

饿汉式单例模式在类加载时就初始化实例,线程安全。

<code>#include <iostream>

class Singleton { -- -->

private:

// 构造函数私有化

Singleton() { }

// 静态实例

static Singleton* instance;

public:

// 获取单例实例

static Singleton* getInstance() {

return instance;

}

void print() {

std::cout << "Hello Singleton..." << std::endl;

}

};

// 在类加载时初始化实例

Singleton* Singleton::instance = new Singleton();

int main() {

Singleton* singleton = Singleton::getInstance();

singleton->print();

return 0;

}

懒汉式单例模式

懒汉式单例模式在第一次使用时初始化实例,懒加载,节省资源,但需要考虑线程安全。

#include <iostream>

#include <mutex>

class Singleton {

private:

static Singleton* instance;

static std::mutex mutex;

Singleton() { }

public:

static Singleton* getInstance() {

if (instance == nullptr) {

std::lock_guard<std::mutex> lock(mutex);

if (instance == nullptr) {

instance = new Singleton();

}

}

return instance;

}

void print() {

std::cout << "Hello Singleton..." << std::endl;

}

};

// 静态成员变量初始化

Singleton* Singleton::instance = nullptr;

std::mutex Singleton::mutex;

int main() {

Singleton* singleton = Singleton::getInstance();

singleton->print();

return 0;

}

2. 工厂设计模式

工厂模式用于创建对象的实例,而不需要指定具体的类。

普通工厂模式

#include <iostream>

#include <string>

class Sender {

public:

virtual void Send() = 0;

virtual ~Sender() { }

};

class MailSender : public Sender {

public:

void Send() override {

std::cout << "This is mail sender..." << std::endl;

}

};

class SmsSender : public Sender {

public:

void Send() override {

std::cout << "This is sms sender..." << std::endl;

}

};

class Factory {

public:

static Sender* produce(const std::string& type) {

if (type == "mail") {

return new MailSender();

} else if (type == "sms") {

return new SmsSender();

} else {

std::cerr << "Invalid type..." << std::endl;

return nullptr;

}

}

};

int main() {

Sender* sender = Factory::produce("mail");

if (sender) {

sender->Send();

delete sender;

}

return 0;

}

多个工厂方法模式

#include <iostream>

class Sender {

public:

virtual void Send() = 0;

virtual ~Sender() { }

};

class MailSender : public Sender {

public:

void Send() override {

std::cout << "This is mail sender..." << std::endl;

}

};

class SmsSender : public Sender {

public:

void Send() override {

std::cout << "This is sms sender..." << std::endl;

}

};

class SendFactory {

public:

Sender* produceMail() {

return new MailSender();

}

Sender* produceSms() {

return new SmsSender();

}

};

int main() {

SendFactory factory;

Sender* sender = factory.produceMail();

if (sender) {

sender->Send();

delete sender;

}

return 0;

}

静态工厂方法模式

#include <iostream>

class Sender {

public:

virtual void Send() = 0;

virtual ~Sender() { }

};

class MailSender : public Sender {

public:

void Send() override {

std::cout << "This is mail sender..." << std::endl;

}

};

class SmsSender : public Sender {

public:

void Send() override {

std::cout << "This is sms sender..." << std::endl;

}

};

class SendFactory {

public:

static Sender* produceMail() {

return new MailSender();

}

static Sender* produceSms() {

return new SmsSender();

}

};

int main() {

Sender* sender = SendFactory::produceMail();

if (sender) {

sender->Send();

delete sender;

}

return 0;

}

抽象工厂模式

#include <iostream>

class Sender {

public:

virtual void Send() = 0;

virtual ~Sender() { }

};

class MailSender : public Sender {

public:

void Send() override {

std::cout << "This is mail sender..." << std::endl;

}

};

class SmsSender : public Sender {

public:

void Send() override {

std::cout << "This is sms sender..." << std::endl;

}

};

class Provider {

public:

virtual Sender* produce() = 0;

virtual ~Provider() { }

};

class SendMailFactory : public Provider {

public:

Sender* produce() override {

return new MailSender();

}

};

class SendSmsFactory : public Provider {

public:

Sender* produce() override {

return new SmsSender();

}

};

int main() {

Provider* provider = new SendMailFactory();

Sender* sender = provider->produce();

if (sender) {

sender->Send();

delete sender;

}

delete provider;

return 0;

}

3. 建造者模式

建造者模式将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。

#include <iostream>

#include <vector>

#include <string>

class Computer {

private:

std::vector<std::string> parts;

public:

void Add(const std::string& part) {

parts.push_back(part);

}

void Show() {

for (const auto& part : parts) {

std::cout << "Component: " << part << " assembled." << std::endl;

}

std::cout << "Computer assembled." << std::endl;

}

};

class Builder {

public:

virtual void BuildCPU() = 0;

virtual void BuildMainboard() = 0;

virtual void BuildHD() = 0;

virtual Computer* GetComputer() = 0;

virtual ~Builder() { }

};

class ConcreteBuilder : public Builder {

private:

Computer* computer;

public:

ConcreteBuilder() {

computer = new Computer();

}

void BuildCPU() override {

computer->Add("CPU");

}

void BuildMainboard() override {

computer->Add("Mainboard");

}

void BuildHD() override {

computer->Add("Hard Disk");

}

Computer* GetComputer() override {

return computer;

}

~ConcreteBuilder() {

delete computer;

}

};

class Director {

public:

void Construct(Builder* builder) {

builder->BuildCPU();

builder->BuildMainboard();

builder->BuildHD();

}

};

int main() {

Director director;

ConcreteBuilder builder;

director.Construct(&builder);

Computer* computer = builder.GetComputer();

computer->Show();

delete computer;

return 0;

}

4. 适配器设计模式

适配器模式将一个类的接口转换成客户端期望的另一个接口,消除由于接口不兼容而导致的类无法一起工作的问题。

类适配器模式

#include <iostream>

class Source {

public:

void method1() {

std::cout << "This is original method..." << std::endl;

}

};

class Targetable {

public:

virtual void method1() = 0;

virtual void method2() = 0;

virtual ~Targetable() { }

};

class Adapter : public Source, public Targetable {

public:

void method2() override {

std::cout << "This is the targetable method..." << std::endl;

}

};

int main() {

Targetable* target = new Adapter();

target->method1();

target->method2();

delete target;

return 0;

}

对象适配器模式

#include <iostream>

#include <string>

using namespace std;

// 对象的适配器模式

// Source 类的定义

class Source {

public:

void method1() {

cout << "This is original method..." << endl;

}

};

// Targetable 接口的定义

class Targetable {

public:

virtual void method1() = 0; // 与原类中的方法相同

virtual void method2() = 0; // 新类的方法

};

// Wrapper 类实现了 Targetable 接口

class Wrapper : public Targetable {

private:

Source* source; // 持有 Source 类的实例

public:

Wrapper(Source* s) : source(s) { }

void method1() override {

source->method1();

}

void method2() override {

cout << "This is the targetable method..." << endl;

}

};

int main() {

Source* source = new Source();

Targetable* targetable = new Wrapper(source);

targetable->method1();

targetable->method2();

delete source;

delete targetable;

return 0;

}

接口的适配器模式

// 接口的适配器模式

#include <iostream>

using namespace std;

// 定义端口接口,提供通信服务

class Port {

public:

virtual void SSH() = 0;

virtual void NET() = 0;

virtual void Tomcat() = 0;

virtual void MySQL() = 0;

};

// 定义抽象类实现端口接口,但是什么事情都不做

class Wrapper : public Port {

public:

void SSH() override { }

void NET() override { }

void Tomcat() override { }

void MySQL() override { }

};

// 提供聊天服务,需要网络功能

class Chat : public Wrapper {

public:

void NET() override {

cout << "Hello World..." << endl;

}

};

// 网站服务器,需要Tomcat容器,MySQL数据库,网络服务,远程服务

class Server : public Wrapper {

public:

void SSH() override {

cout << "Connect success..." << endl;

}

void NET() override {

cout << "WWW..." << endl;

}

void Tomcat() override {

cout << "Tomcat is running..." << endl;

}

void MySQL() override {

cout << "MySQL is running..." << endl;

}

};

int main() {

Port* chatPort = new Chat();

Port* serverPort = new Server();

// 聊天服务

chatPort->NET();

// 服务器

serverPort->SSH();

serverPort->NET();

serverPort->Tomcat();

serverPort->MySQL();

delete chatPort;

delete serverPort;

return 0;

}

5、Decorator Pattern(装饰模式)

装饰模式用于给一个对象增加一些新的功能,动态地为对象增加功能。

// 装饰模式

#include <iostream>

using namespace std;

// Shape 接口

class Shape {

public:

virtual void draw() = 0;

};

// 实现接口的实体类 Rectangle

class Rectangle : public Shape {

public:

void draw() override {

cout << "Shape: Rectangle..." << endl;

}

};

// 实现接口的实体类 Circle

class Circle : public Shape {

public:

void draw() override {

cout << "Shape: Circle..." << endl;

}

};

// 创建实现了 Shape 接口的抽象装饰类 ShapeDecorator

class ShapeDecorator : public Shape {

protected:

Shape* decoratedShape;

public:

ShapeDecorator(Shape* shape) : decoratedShape(shape) { }

void draw() override {

decoratedShape->draw();

}

};

// 创建扩展自 ShapeDecorator 类的实体装饰类 RedShapeDecorator

class RedShapeDecorator : public ShapeDecorator {

public:

RedShapeDecorator(Shape* shape) : ShapeDecorator(shape) { }

void draw() override {

decoratedShape->draw();

setRedBorder();

}

void setRedBorder() {

cout << "Border Color: Red" << endl;

}

};

int main() {

Shape* circle = new Circle();

Shape* redCircle = new RedShapeDecorator(new Circle());

Shape* redRectangle = new RedShapeDecorator(new Rectangle());

cout << "Circle with normal border" << endl;

circle->draw();

cout << "\nCircle of red border" << endl;

redCircle->draw();

cout << "\nRectangle of red border" << endl;

redRectangle->draw();

delete circle;

delete redCircle;

delete redRectangle;

return 0;

}

6、Strategy Pattern(策略模式)

策略模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换。

// 策略模式

#include <iostream>

using namespace std;

// 抽象算法的策略类 Strategy

class Strategy {

public:

virtual void AlgorithmInterface() = 0; // 算法方法

};

// 具体算法A

class ConcreteStrategyA : public Strategy {

public:

void AlgorithmInterface() override {

cout << "算法A的实现" << endl;

}

};

// 具体算法B

class ConcreteStrategyB : public Strategy {

public:

void AlgorithmInterface() override {

cout << "算法B的实现" << endl;

}

};

// 具体算法C

class ConcreteStrategyC : public Strategy {

public:

void AlgorithmInterface() override {

cout << "算法C的实现" << endl;

}

};

// 上下文,维护一个对策略类对象的引用

class Context {

private:

Strategy* strategy;

public:

Context(Strategy* s) : strategy(s) { }

void contextInterface() {

strategy->AlgorithmInterface();

}

};

int main() {

Context* context;

context = new Context(new ConcreteStrategyA());

context->contextInterface();

context = new Context(new ConcreteStrategyB());

context->contextInterface();

context = new Context(new ConcreteStrategyC());

context->contextInterface();

delete context;

return 0;

}

7、Proxy Pattern(代理模式)

代理模式用于控制对原对象的引用,分为静态代理和动态代理。

// 代理模式

#include <iostream>

using namespace std;

// 服务接口

class IService {

public:

virtual void service() = 0;

};

// 被代理类

class Service : public IService {

public:

void service() override {

cout << "被代理对象执行相关操作" << endl;

}

};

// 代理类

class ProxyService : public IService {

private:

IService* service;

public:

ProxyService(IService* s) : service(s) { }

void service() override {

cout << "开始执行service()方法" << endl;

service->service();

cout << "service()方法执行完毕" << endl;

}

};

int main() {

IService* service = new Service();

ProxyService* proxyService = new ProxyService(service);

proxyService->service();

delete service;

delete proxyService;

return 0;

}

8、Template Method Pattern(模板方法模式)

模板方法模式定义了一个算法的骨架,将一些步骤延迟到子类中实现,使得子类可以重新定义算法的步骤。

// 模板方法模式

#include <iostream>

#include <string>

#include <ctime>

using namespace std;

// 员工抽象类

class Worker {

protected:

string name;

public:

Worker(const string& n) : name(n) { }

void workOneDay() {

cout << "-----------------work start----------------" << endl;

enterCompany();

work();

exitCompany();

cout << "-----------------work end----------------" << endl;

}

virtual void work() = 0; // 工作抽象方法

virtual bool isNeedPrintDate() {

return false; // 钩子方法,默认不打印日期

}

private:

void enterCompany() {

cout << name << "---进入公司" << endl;

}

void exitCompany() {

if (isNeedPrintDate()) {

time_t now = time(nullptr);

cout << "---" << ctime(&now) << "--->" << endl;

}

cout << name << "---离开公司" << endl;

}

};

// 测试人员类

class QAWorker : public Worker {

public:

QAWorker(const string& n) : Worker(n) { }

void work() override {

cout << name << "---测试产品质量" << endl;

}

};

// HR 类

class HRWorker : public Worker {

public:

HRWorker(const string& n) : Worker(n) { }

void work() override {

cout << name << "---招聘新员工" << endl;

}

};

// 程序猿类

class ITWorker : public Worker {

public:

ITWorker(const string& n) : Worker(n) { }

void work() override {

cout << name << "---撰写代码" << endl;

}

bool isNeedPrintDate() override {

return true; // 钩子方法,打印日期

}

};

int main() {

QAWorker* qaWorker = new QAWorker("测试人员");

qaWorker->workOneDay();

HRWorker* hrWorker = new HRWorker("莉莉姐");

hrWorker->workOneDay();

ITWorker* itWorker = new ITWorker("jingbin");

itWorker->workOneDay();

delete qaWorker;

delete hrWorker;

delete itWorker;

return 0;

}

这些 C++ 代码可以帮助读者更好地理解设计模式及其在实际代码中的应用。



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。