cbel
cbel

Reputation: 1077

Does Strategy Pattern permits states?

All references of strategy pattern I'd seen shows that the concrete has no state(member data). But I wonder if it can have, it may be sometimes useful, for example:

class bark_strategy {
public:
    virtual void execute() = 0;
};

class bowwow : public bark_strategy {
public:
    bowwow(unsigned int t) : m_tired(t), m_count(0) {}
    virtual void execute() override
    {
        if (m_count < m_tired)
        {
            ++m_count;
            std::cout << "bowwowwowwowwowwowwow..." << std::endl;
        }
        else
        {
            std::cout << "bow..." << std::endl;
        }
    }

private:
    unsigned int m_tired;
    unsigned int m_count;   
};

Does Strategy Pattern permits states? If not, what's the drawback?

Upvotes: 1

Views: 77

Answers (1)

WiSaGaN
WiSaGaN

Reputation: 48087

Of course you can use states. Design patterns are just conventions for people to communicate ideas of specific design. It does not try to restrict you.

In this case, strategy pattern is a way to abstract out different ways of executing, so that user can decide at run-time how they want to execute. And you have used polymorphism to implement it. "States" is just another part of your program design, which has nothing to do with the pattern. You will need to consider whether that's good from your program's point but not whether it is a pattern.

Even there are some kind of design that interferes with the strategy pattern or so, which makes it not of a strategy pattern, it's still fine as long as it suits your design goal.

Upvotes: 2

Related Questions