software architecture - how should a plugin get information from caller (c++?) - c++

say that we have some process and it uses a plugin to do an unknown implementation -
so the plugin implements an header and called with virtual functions to do some work.
now what if the plugin wants data back from the main process? get some gui stuff or other changed states of objects that cannot given at the time the virtual function was called ?
easiest thing to do is to make the interface bi -directional so plugin can ask questions
but it feels wrong to me.
i have read that interfaces should be one directional and actually i should have input and output interface for the plugin , but is still not answering the basic question of how to get data from the caller?
class A
{
...
void doWork()
{
plugin->doWorkInPlugin();
}
private:
MYinterafce* plugin;
}
class MYinterface
{
virtual doWorkInPlugin();
...
}
class MYPlugin : public MYinterface
{
doWorkInPlugin();
{
**** i want to know something in class A or GUI status or class Z ***
output->hello("blah");
}
private:
MYoutputInterface *output;
}
update * clarify why i use empty parameter in the function *
the thing is doWorkInPlugin is long running function ,mayby in thread needs to know changed states of objects that changed after the call has been made

Related

How to structure this without introducing circular includes?

I am trying to figure out how to structure my game. I want to pass my "managers" down the hiearchy instead of making them global. But I ran into a problem. One of my managers updates scenes. It needs to pass Application reference to scenes, as application contains quit method. But my Application holds and updates this SceneManager. So my Application now includes SceneManager as it needs to update it, and my SceneManager includes Application as it needs to pass Application reference to scenes.
Basically Application holds all managers, SceneManager passes Application reference to Scenes, Scenes use managers obtained from Application reference.
// In application
sceneManager.updateScenes(*this);
// In SceneManager
currentScene.update(application)
// In scene
application.getSceneManager().doSomething()
Could anyone suggest me how to elegantly structure this part of my game? I know about forward declarations, but I would like to know if there is a solution without the need to make forward declarations.
I could use globals, but I would rather not.
One common (but not the only) solution to this problem is to have Scene communicate with Application through an interface which Application implements, rather than by direct reference.
This has the additional benefit of more clearly expressing what exactly Scene (and other dependencies) need to call out to.
For example:
interface ISceneHandler {
void Quit(); // Request that we quit the game.
}
class Application : ISceneHandler {
private SceneManager sceneManager;
public Application() {
// Pass ourself as the handler.
sceneManager = new SceneManager(this);
}
public void Quit() { ... }
}
class SceneManager {
private ISceneHandler handler;
public SceneManager(ISceneHandler handler) {
this.handler = handler;
}
public void SomeEvent() {
this.handler.Quit();
}
}

Accessing document files from dialog class in mfc, sdi

I am new to mfc, so I don't know if I will explain my problem correctly but I'll try.
So I built a puzzle game in mfc, and I want to implement high score system. When the game is over, the dialog pops up, where you put your name, and name is written in the external txt file. So, I have Dialog class, where I implement stuff about putting in your name, and sending it to a txt file, but the problem is that I can't access the info about the score, which is stored in the ProjectDoc class, so I can't link the name of the player and the score.
So the question is how to access files from ProjectDoc class from dialog class.
The solution offered by IInspectable and thomiel works great if you have one (or a few) parameter.
Another extreme would be to pass a pointer to the Document and let the Dialog pull whatever it needs out of it, but that would violate "need to know" policy.
I would suggest to define an interface (abstract class) IHighScoreProvider with required accessors, for example:
class IHighScoreProvider
{
public:
virtual int GetGameScore() = 0;
virtual std::string GetPlayerName() = 0;
};
Then derive your Document from it and implement those methods. And pass that interface pointer to your dialog.
Submit the score as parameter in the constructor of you dialog class:
CHighscoreDlg::CHighscoreDlg(int score)
{
m_score = score; // store in private class member variable
}
...
...
void CPuzzleView::EndGame()
{
CHighscoreDlg hs(GetDocument()->m_gamescore);
hs.DoModal();
}

Command design pattern and user interaction

I am implementing command design pattern but my command needs to ask user for file name. I am not sure how can command ask for it?
The gang of four book seems to touch this issue but I am not quite clear. Below is my code (pseudo code to be correct and written on fly).
class OpenDocumentCommand : public Command
{
virtual char * AskUserForFileName();
virtual void Execute();
Application _App;
}
void OpenDocumentCommand::Execute()
{
char * fileName = AskUserForFileName();
_App.OpenDocument( fileName );
}
Now in typical simple example, AskUserForFileName() can be cin and cout but how can it ask for file name in a proper Windows application? It should open File Explorer and user can select file name?
Does it means it has to be tighly coupled with windows? My plan is to use this code both on Windows and iOS so I would like a decoupled solution.
To minimize coupling between your command and the window you should at least insert an abstraction layer between them. In many MVVM implementations you can find a "Modal Dialog"-interface that hides the implementation details of the window from the calling ViewModel.
This interface contains at least a single method "ShowDialog()", but it can also take a ViewModel as a parameter and returns a callback to inform the caller when it gets closed by the user.
Here is an example:
public interface IModalWindow
2 {
3 bool? DialogResult { get; set; }
4 event EventHandler Closed;
5 void Show();
6 object DataContext { get; set; }
7 void Close();
8 }

Passing application objects into lower level classes

I wasn't really sure how to search for this question.
I'm doing an embedded system design with the following scenario.
I have a main application class that needs to create a bunch of hardware interfaces such as a keypad, display, communication ports, etc... a whole slew of stuff
Now I have all these objets in the main application that I can use which is great
The application class contains a few sub classes that it can go into and stay for a while. One example is a menu class that it enters and runs inside that class until the menu is closed
I need the menu class to also interact with a lot of a hardware objects that were created at the application level
What is the best way to go about this without using global variables? Is there a good solution to this problem?
I could pass each object into the menu class, but I don't want to create a constructor with 20 arguments. My current solution is to put all the objects into a structure and pass that structure into the sub-class constructor. That way they also have access.
The part that bugs me about this approach is that I have to define the structure outside of the application which I don't really like. Something just keeps telling me it's not the best solution.
Open to any suggestions.
Presumably, there is ONE keypad - thus only one "Keypad Interface Object", right? Similarly with Display [ok, there may be two displays, but still].
So my suggestion would be to have a registration and a "container" that holds the registered interfaces something like this:
class KeyPad
{
public:
int getKeyPressed();
};
class Display
{
public:
OutputText(std::string msg);
};
... bunch of other stuff ...
class HardwareRegistry
{
priviate:
Keypad *keypad;
Display *display;
static HardwareRegistry *myself;
public:
Keypad* GetKeypad() { return keypad; }
Display* GetDisplay() { return display; }
void RegisterKeypad(Keypad *akeypad) { keypad = akeypad; }
void RegisterDisplay(Display *adisplay) { display = adisplay; }
static HardwareRegistry* GetHwRegistry()
{
if (!myself) myself = new HardwareRegistry;
ASSERT(myself); // If we don't have a pointer now, panic!
return myself;
}
};
Then you just have a Singleton Pattern to provide your HardwareRegistry, and register the devices as you create them during hardware initialization.
Of course, if you support different kinds of Keypads, Displays, etc, then you would implement those with a "interface baseclass", and the registry returns the KeypadBase type, for example.

Common Design for Console and GUI

I am designing a little game for my own fun's and training's sake. The real identity of the game being quite irrelevant for my actual question, suppose it's the Mastermind game (which it actually is :)
My real goal here is to have an interface IPlayer which will be used for any player: computer or human, console or gui, local or network. I am also intending to have a GameController, which will deal with just two IPlayers.
the IPlayer interface would look something like this:
class IPlayer
{
public:
//dtor
virtual ~IPlayer()
{
}
//call this function before the game starts. In subclasses,
//the overriders can, for example, generate and store the combination.
virtual void PrepareForNewGame() = 0;
//make the current guess
virtual Combination MakeAGuess() = 0;
//return false if lie is detected.
virtual bool ProcessResult(Combination const &, Result const &) = 0;
//Answer to opponent's guess
virtual Result AnswerToOpponentsGuess(Combination const&) = 0;
};
The GameController class would do something like this:
IPlayer* pPlayer1 = PlayerFactory::CreateHumanPlayer();
IPlayer* pPlayer1 = PlayerFactory::CreateCPUPlayer();
pPlayer1->PrepareForNewGame();
pPlayer2->PrepareForNewGame();
while(no_winner)
{
Guess g = pPlayer1->MakeAguess();
Result r = pPlayer2->AnswerToOpponentsGuess(g);
bool player2HasLied = ! pPlayer1->ProcessResult(g, r);
etc.
etc.
}
By this design, I am willing to make GameController class immutable, that is, I stuff the just game rules in it, and nothing else, so since the game itself is established, this class shouldn't change. For a console game this design would work perfectly. I would have HumanPlayer, which in its MakeAGuess method would read a Combination from the standard input, and a CPUPlayer, which would somehow randomly generate it etc.
Now here's my problem: The IPlayer interface, along with the GameController class, are synchronous in their nature. I can't imagine how I would implement the GUI variant of the game with the same GameController when the MakeAGuess method of GUIHumanPlayer would have to wait for, for example, some mouse movements and clicks. Of course, I could launch a new thread which would wait for user input, while the main thread would block, so as to imitate synchronous IO, but somehow this idea disgusts me. Or, alternatively, I could design both the controller and player to be asynchronous. In this case, for a console game, I would have to imitate asynchronousness, which seems easier than the first version.
Would you kindly comment on my design and my concerns about choosing synchronous or asynchronous design? Also, I am feeling that I put more responsibility on the player class than GameController class. Etc, etc.
Thank you very much in advance.
P.S. I don't like the title of my question. Feel free to edit it :)
Instead of using return values of the various IPlayer methods, consider introducing an observer class for IPlayer objects, like this:
class IPlayerObserver
{
public:
virtual ~IPlayerObserver() { }
virtual void guessMade( Combination c ) = 0;
// ...
};
class IPlayer
{
public:
virtual ~IPlayer() { }
virtual void setObserver( IPlayerObserver *observer ) = 0;
// ...
};
The methods of IPlayer should then call the appropriate methods of an installed IPlayerObserver instead of returning a value, as in:
void HumanPlayer::makeAGuess() {
// get input from human
Combination c;
c = ...;
m_observer->guessMade( c );
}
Your GameController class could then implement IPlayerObserver so that it gets notified whenever a player did something interesting, like - making a guess.
With this design, it's perfectly fine if all the IPlayer methods are asynchronous. In fact, it's to be expected - they all return void!. Your game controller calls makeAGuess on the active player (this might compute the result immediately, or it might do some network IO for multiplayer games, or it would wait for the GUI to do something) and whenever the player did his choice, the game controller can rest assured that the guessMade method will be called. Furthemore, the player objects still don't know anything about the game controller. They are just dealing with an opaque 'IPlayerObserver' interface.
The only thing making this different for the GUI as compared to the console is that your GUI is event driven. Those events take place on the GUI thread, and therefore, if you host the Game code on the GUI thread, you have a problem: Your call to have the player make a move blocks the GUI thread, and this means you can't get any events until that call returns. [EDIT: Inserted the following sentence.] But the call can't return until it gets the event. So you're deadlocked.
That problem would go away if you simply host the game code on another thread. You'd still need to synchronize the threads, so MakeAGuess() doesn't return until ready, but it's certainly doable.
If you want to keep everything single-threaded you may want to consider a different model. Game could notify Players it's their turn with an event but leave it to players to initiate operations on the Game.