C++ 语言 设计模式与 SOLID 原则

C++阿木 发布于 2025-06-14 2 次阅读


阿木博主一句话概括:C++ 设计模式与 SOLID 原则实践解析

阿木博主为你简单介绍:本文将围绕C++语言,探讨设计模式与SOLID原则在软件开发中的应用。通过实际代码示例,分析如何运用这些原则来提高代码的可维护性、可扩展性和可复用性。

一、

设计模式与SOLID原则是软件工程中非常重要的概念,它们可以帮助开发者编写出更加清晰、高效和可维护的代码。本文将结合C++语言,通过实际代码示例,深入解析设计模式与SOLID原则在软件开发中的应用。

二、设计模式

设计模式是一套被反复使用、多数人知晓、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。

以下是一个使用工厂模式创建不同形状的示例:

cpp
include
include

// 抽象产品
class Shape {
public:
virtual void draw() = 0;
virtual ~Shape() {}
};

// 具体产品:圆形
class Circle : public Shape {
public:
void draw() override {
std::cout << "Drawing Circle" << std::endl;
}
};

// 具体产品:矩形
class Rectangle : public Shape {
public:
void draw() override {
std::cout << "Drawing Rectangle" << std::endl;
}
};

// 抽象工厂
class ShapeFactory {
public:
virtual std::unique_ptr createShape(const std::string& shapeType) = 0;
virtual ~ShapeFactory() {}
};

// 具体工厂:圆形工厂
class CircleFactory : public ShapeFactory {
public:
std::unique_ptr createShape(const std::string& shapeType) override {
if (shapeType == "circle") {
return std::make_unique();
}
return nullptr;
}
};

// 具体工厂:矩形工厂
class RectangleFactory : public ShapeFactory {
public:
std::unique_ptr createShape(const std::string& shapeType) override {
if (shapeType == "rectangle") {
return std::make_unique();
}
return nullptr;
}
};

// 客户端代码
int main() {
ShapeFactory circleFactory = new CircleFactory();
std::unique_ptr circle = circleFactory->createShape("circle");
circle->draw();

ShapeFactory rectangleFactory = new RectangleFactory();
std::unique_ptr rectangle = rectangleFactory->createShape("rectangle");
rectangle->draw();

delete circleFactory;
delete rectangleFactory;

return 0;
}

三、SOLID原则

SOLID原则是一组指导原则,用于指导软件设计,确保代码的可维护性和可扩展性。

1. 单一职责原则(Single Responsibility Principle,SRP)

单一职责原则要求一个类只负责一项职责。以下是一个违反SRP原则的示例:

cpp
class Person {
public:
void setAge(int age) {
if (age age = age;
}

void setFirstName(const std::string& firstName) {
this->firstName = firstName;
}

void setLastName(const std::string& lastName) {
this->lastName = lastName;
}

// ... 其他方法 ...
};

改进后的代码:

cpp
class Person {
public:
void setAge(int age) {
if (age age = age;
}

// ... 其他方法 ...
};

class PersonName {
public:
void setFirstName(const std::string& firstName) {
this->firstName = firstName;
}

void setLastName(const std::string& lastName) {
this->lastName = lastName;
}

// ... 其他方法 ...
};

2. 开放封闭原则(Open/Closed Principle,OCP)

开放封闭原则要求软件实体(类、模块、函数等)应对扩展开放,对修改封闭。以下是一个违反OCP原则的示例:

cpp
class Person {
public:
void setAge(int age) {
if (age age = age;
}

void setFirstName(const std::string& firstName) {
this->firstName = firstName;
}

void setLastName(const std::string& lastName) {
this->lastName = lastName;
}

// ... 其他方法 ...
};

改进后的代码:

cpp
class Person {
public:
virtual void setAttribute(const std::string& attributeName, const std::string& value) {
if (attributeName == "age") {
setAge(std::stoi(value));
} else if (attributeName == "firstName") {
setFirstName(value);
} else if (attributeName == "lastName") {
setLastName(value);
}
// ... 其他属性 ...
}

// ... 其他方法 ...
};

class PersonWithNewAttribute : public Person {
public:
void setNewAttribute(const std::string& value) {
// 设置新的属性
}

// ... 其他方法 ...
};

3. 里氏替换原则(Liskov Substitution Principle,LSP)

里氏替换原则要求子类能够替换其基类对象出现在任何地方。以下是一个违反LSP原则的示例:

cpp
class Square : public Shape {
public:
void draw() override {
std::cout << "Drawing Square" << std::endl;
}
};

class Circle : public Shape {
public:
void draw() override {
std::cout << "Drawing Circle" <draw();
}

int main() {
Square square;
drawShape(&square); // 正常工作

Circle circle;
drawShape(&circle); // 正常工作

// 如果Square和Circle是Shape的子类,并且Shape是抽象类,那么以下代码将抛出异常
// drawShape(new Square()); // 抛出异常
// drawShape(new Circle()); // 抛出异常

return 0;
}

改进后的代码:

cpp
class Square : public Shape {
public:
void draw() override {
std::cout << "Drawing Square" << std::endl;
}
};

class Circle : public Shape {
public:
void draw() override {
std::cout << "Drawing Circle" << std::endl;
}
};

// 客户端代码
void drawShape(Shape& shape) {
shape.draw();
}

int main() {
Square square;
drawShape(square); // 正常工作

Circle circle;
drawShape(circle); // 正常工作

return 0;
}

4. 依赖倒置原则(Dependency Inversion Principle,DIP)

依赖倒置原则要求高层模块不应该依赖于低层模块,二者都应该依赖于抽象。以下是一个违反DIP原则的示例:

cpp
class Person {
public:
void setAge(int age) {
if (age age = age;
}

void setFirstName(const std::string& firstName) {
this->firstName = firstName;
}

void setLastName(const std::string& lastName) {
this->lastName = lastName;
}

// ... 其他方法 ...
};

class PersonService {
public:
void savePerson(Person& person) {
// 保存Person到数据库
}
};

改进后的代码:

cpp
class IPersonRepository {
public:
virtual void savePerson(Person& person) = 0;
virtual ~IPersonRepository() {}
};

class PersonRepository : public IPersonRepository {
public:
void savePerson(Person& person) override {
// 保存Person到数据库
}
};

class PersonService {
private:
IPersonRepository repository;

public:
PersonService(IPersonRepository repository) : repository(repository) {}

void savePerson(Person& person) {
repository->savePerson(person);
}
};

5. 接口隔离原则(Interface Segregation Principle,ISP)

接口隔离原则要求多个特定客户端接口,而不是单一接口,客户端应该只依赖于它所使用的接口。

cpp
// 违反ISP原则的接口
class BigInterface {
public:
void method1() {}
void method2() {}
void method3() {}
// ... 其他方法 ...
};

// 客户端代码
class Client {
public:
void doSomething() {
BigInterface bigInterface = new BigInterface();
bigInterface->method1();
bigInterface->method2();
bigInterface->method3();
// ... 其他方法 ...
delete bigInterface;
}
};

改进后的代码:

cpp
// 遵循ISP原则的接口
class SmallInterface1 {
public:
void method1() {}
void method2() {}
};

class SmallInterface2 {
public:
void method3() {}
void method4() {}
};

// 客户端代码
class Client {
public:
void doSomething() {
SmallInterface1 smallInterface1 = new SmallInterface1();
smallInterface1->method1();
smallInterface1->method2();
delete smallInterface1;

SmallInterface2 smallInterface2 = new SmallInterface2();
smallInterface2->method3();
smallInterface2->method4();
delete smallInterface2;
}
};

四、总结

本文通过C++语言的实际代码示例,深入解析了设计模式与SOLID原则在软件开发中的应用。通过遵循这些原则,我们可以编写出更加清晰、高效和可维护的代码。在实际开发过程中,我们应该不断学习和实践,以提高自己的编程技能。