开发者

C++ Object Oriented Design

开发者 https://www.devze.com 2023-04-03 03:38 出处:网络
class Allegro {}; class Input { private: Allegro allegro1 }; class Graphics { private: Allegro allegro2 }; class Game
class Allegro {};

class Input
{
private:
    Allegro allegro1
};

class Graphics
{
private:
    Allegro allegro2
};

class Game
{
private:
    Input keyBoardinput;
    Graphics Gamegraphics;
};

In the input I need access to Allegro functions related to the user keyboard input. In the Graphics class,I want only functions that will enable me to draw things on the screen, like shapes etc. However the Game class also needs access to Input and Graphics functions while the game is playing.Any ideas on how I can improve the design. I know I can remove the Graphics and Input classes and have all the Allegro functions inside Game class, because what I want to d开发者_C百科o is to separate implementation and logic and to also avoid long classes that do too many things.


Obviously, Graphics and Input should be talking to the same Allegro class. So you should do that: create the Allegro class instance, then use that instance in the constructors for Graphics and Input.


Your Game class should create the instance of Allegro and the same instance should be passed to Input and Graphics, and the latter two will simply hold the reference of the instance.

class Game
{
    Game() : allegro(/*..*/), keyBoardinput(allegro), Gamegraphics(allegro) {}
private:
    Allegro allegro; //actual instance 
    Input keyBoardinput;
    Graphics Gamegraphics;
};

Note that the order of members in Game is important. allegro should be declared before keyBoardinput and Gamegraphics. This makes sure that allegro is created before the rest two, and then you pass allegro (the fully created instance) to the constructors of Input and Graphics.

And then make sure that Input and Graphics hold the reference of allegro which is passed from Game. Don't make a copy of allegro:

class Input
{
public:
    Input(Allegro & allegro) : allegro1(allegro) {}
private:
    Allegro & allegro; //reference  - not copy!
};

class Graphics
{
public:
    Graphics(Allegro & allegro) : allegro1(allegro) {}
private:
    Allegro & allegro; //reference - not copy
};

Note that all of these classes make use of member-initialization-list which is also very important here.

0

精彩评论

暂无评论...
验证码 换一张
取 消