Strategy Pattern paradox

I've reached some sort of paradox while writing my small game. I need an algorithm to decide the winner of the game, but it's a fairly complicated task so i decided to delegate the resposibility to a strategy object, and code a naive(inefficient) algorithm to begin with, then i can easily swap the algorithm for a more effienct one later.

The problem is, that the strategy object needs to know the game, and the game needs to know the strategy object, but as you can see there is no way of doing that since i need to create one object before i create another.
1
2
3
4
5
6
//Wrong code illustrating the concept
Winner_strategy * winner_strategy;
Game * game;

winner_strategy = new Winner_strategy(game);
game = new Game_impl{winner_strategy};


BTW i know that it's best pratice to use unique_ptr, but i don't think it will make a difference here?
Last edited on
Just create a initialize function for each class, that requires a reference to the other class as argument.
cheers!
I suppose that would work.
However i think it's bad pratice if you need to call an initialize function everytime you create an object? Are there no other ways to do it?
Ideally, define a pure interface for the strategy. The game knows only about the strategy interface and accesses the functionality of an implementation through the interface. For instance, std::vector<> knows about allocator requirements (interface); but knows nothing about custom user-defined allocators. std::string knows about and uses the char_traits interface.

To pass information from the game to the strategy object without coupling, the necessary information could be passed as arguments to the functions in the interface.
In a more complex scenario, we may need to create additional classes to encapsulate the information, and then pass them as arguments.

Avoid multi-phase initialisation as far as possible. Instead, favour something like this:
1
2
winner_stratey* strategy = new my_winner_stratey ;
game* the_game( strategy ) ; // pass the strategy interface to the constructor    

In practice, use smart_pointers instead of raw owning pointers.
Thank you JLBorges.
I already use interfaces, but since my real code is fairly long, i decided to cut some of it away for readability and unfortunately failed to demonstrate the use of interfaces. The third line should have been:
winner_strategy = new Naive_winner_strategy(game);

Also your idea of parsing the Game pointer as an argument to the get_winner function, works very nicely :)
Thank you
Topic archived. No new replies allowed.