结构型模式之 外观模式

外观模式(Facade Pattern):外部与一个子系统的通信必须通过一个统一的外观对象进行,为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。外观模式又称为门面模式,它是一种对象结构型模式。

意图:为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。

主要解决:降低访问复杂系统的内部子系统时的复杂度,简化客户端与之的接口。

关键代码:在客户端和复杂系统之间再加一层,这一层将调用顺序、依赖关系等处理好。

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

实现

我们将创建一个 Shape 接口和实现了 Shape 接口的实体类。下一步是定义一个外观类 ShapeMaker

ShapeMaker 类使用实体类来代表用户对这些类的调用。FacadePatternDemo,我们的演示类使用 ShapeMaker 类来显示结果。

//步骤一 创建一个接口
class Shape 
{
public:
    virtual void draw() {}
};
//步骤二 创建实现接口的实体类
class Rectangle: public Shape
{
public:
    void draw()
    {
        std::cout << " Rectangle::draw()" << std::endl;
    }
};

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

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



//步骤 3    创建一个外观类
class ShapeMaker
{
private:
    Shape * circle;
    Shape * rectangle;
    Shape * square;
    bool IsShapeMaked;
public:
    ShapeMaker() 
    {
        circle = new Circle;
        rectangle = new Rectangle;
        square = new Square;
        IsShapeMaked = true;
    }
    ~ShapeMaker() 
    {
        if (IsShapeMaked == true)
        {
            if (circle != NULL)
                delete circle;
            if (rectangle != NULL)
                delete rectangle;
            if (square != NULL)
                delete square;
        }
    }
    void DrawCiecle() { circle->draw(); }
    void DrawRect() { rectangle->draw(); }
    void DrawSquare() { square->draw(); }
};



int main() 
{
    ShapeMaker shapemaker;
    shapemaker.DrawCiecle();
    shapemaker.DrawRect();
    shapemaker.DrawSquare();

    return 0;
}
原文地址:https://www.cnblogs.com/gardenofhu/p/8504474.html