设计模式10 - 外观模式

作者:billy
版权声明:著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处

外观模式

外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。这种类型的设计模式属于结构型模式。这种模式涉及到一个单一的类,该类提供了客户端请求的简化方法和对现有系统类方法的委托调用。

使用场景

  • 为复杂的模块或子系统提供外界访问的模块。
  • 子系统相互独立。
  • 在层析结构中,可以使用外观模式定义系统的每一层的入口。

优缺点

  • 优点:
    1、减少系统相互依赖。
    2、提高灵活性。
    3、提高了安全性。

  • 缺点:
    不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。

注意事项

在层次化结构中,可以使用外观模式定义系统中每一层的入口。

UML结构图

在这里插入图片描述

代码实现

interface.h
创建抽象类 - 图形; 创建具体类 - 圆形、正方形、矩形

#include <iostream>
using namespace std;

class Shape //基类-图形
{
public:
    Shape() {}
    virtual ~Shape() {}

    virtual void draw() = 0;
};

class Square: public Shape  //子类-圆形
{
public:
    void draw() { cout << "draw Square" << endl; }
};

class Circle: public Shape  //子类-正方形
{
public:
    void draw() { cout << "draw Circle" << endl; }
};

class Rectangle: public Shape   //子类-矩形
{
public:
    void draw() { cout << "draw Rectangle" << endl; }
};

shapemaker.h
创建外观类,提供接口给客户使用

#include "interface.h"

class ShapeMaker
{
public:
    ShapeMaker()
    {
        this->circle = new Circle();
        this->square = new Square();
        this->rectangle = new Rectangle();
    }

    void drawCircle() { circle->draw(); }

    void drawSquare() { square->draw(); }

    void drawRectangle() { rectangle->draw(); }

private:
    Shape *circle;
    Shape *square;
    Shape *rectangle;
};

main.cpp
实例应用 - 使用外观类画出不同的图形

#include "shapemaker.h"

int main()
{
    ShapeMaker shapeMaker;
    shapeMaker.drawCircle();
    shapeMaker.drawSquare();
    shapeMaker.drawRectangle();

    return 0;
}

运行结果:
draw Circle
draw Square
draw Rectangle
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值