I think you didn't understand the strategy pattern. The "strategy" is the "functionality", not the "object". Say you have a "Sort" strategy. You can then implement different sorting algorithms as subclasses of the Sort class that operate on a generic sortable object. Then you instantiate one of the algorithm objects so that if some part of your program wants to sort something, it takes the stored concrete strategy object and invoke it through the generic Sort interface. The strategy pattern aims to provide means to operate on objects without adding methods to classes of those objects. In your case you could have a "Peal" strategy that works on "Fruit" class and have two implementations (e.g. ManualPeal and MechanicPeal) that can peal any object implementing the Fruit class (be it Banana or Apple). The strategy should be agnostic to the type of fruit it peals, i.e. it should never care about the details of the fruit -- it is the responsibility of the Fruit class to provide all the needed functionality for the Peal strategy (e.g. though virtual methods reimplemented in particular Fruit subclasses).
Thus looking at your last snippet, your Fruit class should have a "eat" virtual method which is reimplemented by both Banana and Apple. Of course that is regardless of the use of the strategy pattern that does not look very fit for the functionality of your last snippet. If I were to force the pattern there, I would do something along the lines of:
function(iparam) {
FruitEater *eater = 0;
switch(iparam) {
case 1: eater = new AppleEater; break;
case 2: eater = new BananaEater; break;
// ...
}
if(!eater) return;
eater->Eat(object);
delete eater;
}
function(iparam) {
FruitEater *eater = 0;
switch(iparam) {
case 1: eater = new AppleEater; break;
case 2: eater = new BananaEater; break;
// ...
}
if(!eater) return;
eater->Eat(object);
delete eater;
}
To copy to clipboard, switch view to plain text mode
But a simpler equivalent if you don't care about the purity of the API is just:
function(fruit) {
fruit->eat();
}
function(fruit) {
fruit->eat();
}
To copy to clipboard, switch view to plain text mode
The difference is that in the second case the Fruit class needs to have virtual methods and in the first case it doesn't as the virtual method is placed in the Eater class (and its subclasses).
Bookmarks