设计模式(10)-外观模式及实现
基本概念
通过引入一个外观类(Facade),将复杂的子系统接口进行封装,为客户端提供一个简单的高层接口。外观类充当了客户端与子系统之间的中间人,处理客户端的请求并将其转发给适当的子系统。外观模式并不在系统中添加新功能,它只是提供了一个更简洁的接口,以简化客户端的操作。
优点:
● 简化接口:客户端只需要与外观类交互,无需了解底层子系统的复杂性。
● 降低耦合:外观模式将客户端与子系统解耦,使得系统的变化不会影响客户端代码。
● 提高可维护性:由于外观模式将子系统封装起来,修改子系统的实现不会影响客户端代码,从而提高了系统的可维护性。
● 支持松散耦合:外观模式可以帮助系统中的不同模块之间实现松散耦合,从而支持模块的独立开发和测试。
https://gitee.com/want-to-lose-another-30-jin/design-pattern-implementation
设计模式具体实现
角色
1、Facade(外观角色):为子系统提供外界访问的接口。
2、SubSystem(子系统角色):实现系统的部分功能,同时可以被外观类调用。
java实现
package shejimoshi.waiguanmoshi;
// 子系统角色
public interface Shape {
void draw();
}
package shejimoshi.waiguanmoshi;
public class Rectangle implements Shape {
public void draw() {
System.out.println("Rectangle : Draw a rectangle");
}
}
package shejimoshi.waiguanmoshi;
public class Square implements Shape {
public void draw() {
System.out.println("Square : Draw a square");
}
}
package shejimoshi.waiguanmoshi;
// 外观角色
public class ShapeMaker {
private Shape shape;
public void setShape(Shape shape) {
this.shape = shape;
}
public void drawShape() {
shape.draw();
}
}
package shejimoshi.waiguanmoshi;
public class client {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();
shapeMaker.setShape(new Rectangle());
shapeMaker.drawShape();
shapeMaker.setShape(new Square());
shapeMaker.drawShape();
}
}
c++实现
#include<iostream>
// 子系统角色
class Shape {
public:
virtual void draw() = 0;
virtual ~Shape() {}
};
class Rectangle : public Shape {
void draw() override {
std::cout << "Rectangle : Draw a rectangle" << std::endl;
}
};
class Square : public Shape {
void draw() override {
std::cout << "Square : Draw a square" << std::endl;
}
};
// 外观角色
class ShapeMaker {
private:
Shape* shape;
public:
void setShape(Shape* s) {
shape = s;
}
void drawShape() {
shape->draw();
}
};
// 客户端代码
int main() {
ShapeMaker shapeMaker;
shapeMaker.setShape(new Rectangle());
shapeMaker.drawShape();
shapeMaker.setShape(new Square());
shapeMaker.drawShape();
return 0;
}