如何访问装饰类的方法?

时间:2017-04-22 14:46:13

标签: c++ decorator

我有以下程序实现了一个基本的装饰器类,但装饰器也有自己的成员函数,我希望可以访问。在下面的例子中,我想做一些像finalMouse-> rightMouseButton-> click()。这种类型的交互甚至可以用装饰器完成,还是另一种设计模式?我想的可能是策略,但这似乎不适用。

由于

#include <string>
#include <iostream>

using namespace std;

typedef enum _location { TOP, SIDE } location;
typedef enum _direction { FORWARD, BACKWARD } direction;

class MouseAbstract
{
    public:
        virtual string printConfiguration() = 0;
};

class Mouse : public MouseAbstract
{
    public:
        Mouse(string n) { name = n; };
        string printConfiguration() {
            return name + " Configuration: ";
        }
    private:
        string name;
};

class MouseConfigurationAddon : public MouseAbstract
{
    public:
        MouseConfigurationAddon(MouseAbstract* add, location loc, string desc) {
            addon = add;
            mLocation = loc;
            description = desc;
        };
        string printConfiguration() {
            string outLoc = (mLocation == TOP) ? "Location: Top" : "Location: Side";
            return addon->printConfiguration() + "\n\nAddon: " + description + ", " + outLoc;
        }
    protected:
        MouseAbstract* addon;
        location mLocation;
        string description;
};

class Button : public MouseConfigurationAddon
{
    public:
        Button(MouseAbstract* add, location loc, string desc) : MouseConfigurationAddon(add, loc, desc) {};
        string click() {
            return description + " has been clicked.";
        };
};

class ScrollWheel : public MouseConfigurationAddon
{
public:
    ScrollWheel(MouseAbstract* add, location loc, string desc) : MouseConfigurationAddon(add, loc, desc) {};
    string spin(direction dir, double rotations) {
        string outDir = (mLocation == FORWARD) ? "forward" : "backward";
        return description + " has been spun " + outDir + to_string(rotations) + " rotations.";
    };
};

int main() {
    Mouse* baseMouse = new Mouse("My Gaming Mouse");
    Button* rightMouseButton = new Button(baseMouse, TOP, "Right Mouse Button");
    Button* leftMouseButton = new Button(rightMouseButton, TOP, "Left Mouse Button");
    Button* sideButton1 = new Button(leftMouseButton, SIDE, "Side Button 1");
    Button* sideButton2 = new Button(sideButton1, SIDE, "Side Button 2");
    ScrollWheel* finalMouse = new ScrollWheel(sideButton2, TOP, "Scroll Wheel");

    cout << finalMouse->printConfiguration() << endl;

    delete finalMouse;
    return 0;
}

0 个答案:

没有答案