使用 c++++ 设计模式解决常见编程问题:工厂模式:创建大量相关对象。装饰器模式:扩展类的行为。责任链模式:将对象串联在一起处理请求。
使用设计模式解决常见的 C++ 编程问题
设计模式是一种经过验证的解决方案,可以解决软件设计中常见的编程问题。通过使用设计模式,您可以提高代码的可重用性、可维护性和灵活性。
以下是如何使用 C++ 设计模式来解决常见 C++ 编程问题的实战案例:
立即学习“C++免费学习笔记(深入)”;
问题:创建大量相关对象
工厂模式可以创建对象而不指定类。这对于创建大量相关对象非常有用,因为您可以将对象创建过程与实际类型的选择解耦。
代码示例:
class Shape {
public:
virtual void draw() = 0;
};
class Rectangle : public Shape {
public:
void draw() {
// 绘制矩形
}
};
class Circle : public Shape {
public:
void draw() {
// 绘制圆形
}
};
class ShapeFactory {
public:
static Shape* createShape(const std::string& shapeType) {
if (shapeType == "rectangle") {
return new Rectangle();
} else if (shapeType == "circle") {
return new Circle();
} else {
return nullptr;
}
}
};
int main() {
std::vector<Shape*> shapes;
shapes.push_back(ShapeFactory::createShape("rectangle"));
shapes.push_back(ShapeFactory::createShape("circle"));
for (Shape* shape : shapes) {
shape->draw();
}
return 0;
}
问题:扩展类的行为
装饰器模式允许动态地将行为添加到对象。这对于在不修改现有代码的情况下扩展类的行为非常有用。
代码示例:
class Shape {
public:
virtual void draw() = 0;
};
class Rectangle : public Shape {
public:
void draw() {
// 绘制矩形
}
};
class ColoredShape : public Shape {
public:
ColoredShape(Shape* shape, const std::string& color)
: _shape(shape), _color(color) {}
void draw() {
_shape->draw();
std::cout << " with color " << _color << std::endl;
}
private:
Shape* _shape;
std::string _color;
};
int main() {
Shape* rectangle = new Rectangle();
Shape* coloredRectangle = new ColoredShape(rectangle, "red");
rectangle->draw();
coloredRectangle->draw();
return 0;
}
问题:将对象串联在一起
责任链模式将一系列处理程序组织成链条。当一个对象收到请求时,它将请求传递给下一处理程序,直到请求被处理。
代码示例:
class Handler {
public:
virtual bool handle(int request) = 0;
Handler* nextHandler() {
return _nextHandler;
}
void setNextHandler(Handler* nextHandler) {
_nextHandler = nextHandler;
}
private:
Handler* _nextHandler;
};
class ConcreteHandler1 : public Handler {
public:
bool handle(int request) {
if (request < 10) {
std::cout << "ConcreteHandler1 handled request " << request << std::endl;
return true;
} else {
return false;
}
}
};
class ConcreteHandler2 : public Handler {
public:
bool handle(int request) {
if (request >= 10 && request < 20) {
std::cout << "ConcreteHandler2 handled request " << request << std::endl;
return true;
} else {
return false;
}
}
};
int main() {
Handler* handler1 = new ConcreteHandler1();
Handler* handler2 = new ConcreteHandler2();
handler1->setNextHandler(handler2);
int request = 15;
handler1->handle(request);
return 0;
}
使用设计模式可以帮助您编写更灵活、更可重用的 C++ 代码。通过将常见的设计模式集成到您的项目中,您可以提高开发效率并创建更健壮的应用程序。