Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Strategy pattern

Tags:

In the past, I have seen the strategy pattern explained as a mechanism which allows the user of a function/class to provide their own functionality for that function/class.

I had always been taught that the way to implement the pattern was by taking function pointers into your classes/functions and calling them internally, thus allowing the programmer to provide their own "strategy" which would be used internally by those functions and objects.

Looking around more recently, I see that the strategy pattern always seems to be explained/defined through the use of an inheritance hierarchy like so:

Strategy pattern implementation

is this a difference of opinion/implementation, or is the function pointer passing not really a variation of the strategy pattern? I'm mostly interested so I don't confuse people when I comment or explain my code :)

like image 980
John Humphreys Avatar asked Sep 06 '11 18:09

John Humphreys


People also ask

What is C pattern design?

Design Patterns in the object-oriented world is a reusable solution to common software design problems that occur repeatedly in real-world application development. It is a template or description of how to solve problems that can be used in many situations. "A pattern is a recurring solution to a problem in a context."

What is strategy as a pattern?

As a Plan, strategy needs to be developed in advance and with purpose. As a Ploy, strategy is a means of outsmarting the competition. With strategy as a Pattern, we learn to appreciate that what was successful in the past can lead to success in the future.

What is the common class pattern strategy?

Solution. The Strategy pattern suggests that you take a class that does something specific in a lot of different ways and extract all of these algorithms into separate classes called strategies. The original class, called context, must have a field for storing a reference to one of the strategies.

Where is strategy pattern used?

Use the Strategy pattern when you want to use different variants of an algorithm within an object and be able to switch from one algorithm to another during runtime. Use the Strategy when you have a lot of similar classes that only differ in the way they execute some behavior.


1 Answers

You simply have to use inheritance in languages without function pointers (read: Java).

Personally, I would prefer std::function over raw function pointers, because it accepts a wider range of arguments and allows you to maintain state in the strategy object.

Also, if you already know the strategy at compile-time, you can even use templates and thus save both the space and runtime overhead of function pointers and std::function objects.

like image 115
fredoverflow Avatar answered Oct 23 '22 14:10

fredoverflow