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 }
Related
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
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();
}
For testing software with Google Espresso test-framework I have following issue:
At start of the program, a splash screen starts and initialises the entire application. After this, I start an Activity which asks for input.
In Espresso, the application starts and the test starts with following code:
onView(withId(R.id.chooseBookTitle)).perform(click());
This crashes, because the display still shows the splash screen and the chooseBookTitle is only visible afterwards. How to prevent that Google-Espresso will click the key before it is there?
(I don't want to insert wait loops, but keep it event driven. In worse case, I go back to Robotium)
Please check the IdlingResource interface:
As mentioned by Stefano Dacchille (see sample below) you must create an idling ressource implementation that waits to become idle:
public class WaitForSomethingResource implements IdlingResource {
ResourceCallback mResourceCallback;
private boolean isIdle;
#Override
public String getName() {
return WaitForSomethingResource.class.getName();
}
#Override
public void registerIdleTransitionCallback(
ResourceCallback resourceCallback) {
mResourceCallback = resourceCallback;
}
#Override
public boolean isIdleNow() {
return isIdle;
}
/**
* Register an listener, use an event bus or something
* else to get notified about any change you want to track.
*/
public void onProgressChanged() {
isIdle = true;
if (isIdle && mResourceCallback != null) {
mResourceCallback.onTransitionToIdle();
}
}
}
After that, you have to register the IdlingResource implementation within the tests setUp() or #before method by writing:
Espresso.registerIdlingResource(waitForSomethingResource)
Sample:
http://dev.jimdo.com/2014/05/09/wait-for-it-a-deep-dive-into-espresso-s-idling-resources/
API Doc:
http://developer.android.com/reference/android/support/test/espresso/IdlingResource.html#isIdleNow()
From what I see, you should open directly the activity that contains R.id.chooseBookTitle, otherwise your view will never be on the screen so your test will always fail because Espresso can't find the specified view.
Otherwise, I use Thread.sleep(...) before I do some tests to make the tests wait. Try it before calling onView(withId(R.id.chooseBookTitle)).perform(click()); and see if it's working.
Good luck!
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.
I was studying the Model-View-Controller design pattern and i understand the concept behind the pattern theorotically, but I wanted to get a peek at how one would actually put it to practice.
Wikipedia mentions Wt - Web toolkit, CppCMS and some other standard implementations which use the pattern however I have not been familiar with these, and I was just hoping and
will be really grateful If anyone can provide some sample code(hopefully C++) which implements the pattern and explains the theory of the pattern being put to practice.
Here's a quick example I made (didn't try compiling it, let me know if there's errors):
class Button; // Prewritten GUI element
class GraphGUI {
public:
GraphGUI() {
_button = new Button("Click Me");
_model = new GraphData();
_controller = new GraphController(_model, _button);
}
~GraphGUI() {
delete _button;
delete _model;
delete _controller;
}
drawGraph() {
// Use model's data to draw the graph somehow
}
...
private:
Button* _button;
GraphData* _model;
GraphController* _controller;
};
class GraphData {
public:
GraphData() {
_number = 10;
}
void increaseNumber() {
_number += 10;
}
const int getNumber() { return _number; }
private:
int _number;
};
class GraphController {
public:
GraphController(GraphData* model, Button* button) {
__model = model;
__button = button;
__button->setClickHandler(this, &onButtonClicked);
}
void onButtonClicked() {
__model->increaseNumber();
}
private:
// Don't handle memory
GraphData* __model;
Button* __button;
};
Ignoring the implementation of Button, basically this program will use GraphGUI to display a graph that will change when a button is pressed. Let's say it's a bar graph and it will get taller.
Since the model is independent of the view (the button), and the controller handles the communication between the two, this follows the MVC pattern.
When the button is clicked, the controller modifies the model via the onButtonClicked function, which the Button class knows to call when it is clicked.
The beauty of this is since the model and view are completely independent, the implementation of each can drastically change and it won't affect the other, the controller might simply have to make a few changes. If the model in this case calculated some result based off some database data, then clicking the button could cause this to happen, but the button implementation wouldn't have to change. Or, instead of telling the controller when a click occurs, maybe it can tell the controller when the button is moused-over. The same changes are applied to model, regardless of what triggered the changes.
A simple text editor could be designed based on MVC. Think of the string class as the model, where data is stored. We might have a class called SimpleTextView which displays the text in the string attached to it, as it is. A class called KeyboardEventHandler can act as the controller. The controller will notify the view about new keyboard events. The view in turn modifies the model (like appending or removing text). The changes in the model is reflected on all views attached to it. For instance, there might be another view called HtmlView attached to the string object manipulated from within the SimpleTextView. If the user enters valid HTML tags in the SimpleTextView, the HtmlView will display the formatted output - real-time.
There are couple of complete MVC examples, plus discussion, in ch 2 of an introduction to programming in Python 3.x that I wrote (I've not completed ch 3 etc., that project's been on ice for some time -- Python community really like angry swarm of bees when discovered I'd written that Python was perhaps not suitable for very large scale development, so it became difficult to get sensible feedback). It's available in PDF format from Google Docs. I don't know how well it maps to common MVC implementations, I was mostly concerned with getting the general idea across. :-)
Cheers & hth.,
PS: There's a nice table of contents in the PDF file but Google Docs doesn't show it. You'd need to dl and use Foxit or Acrobat or some other PDF viewer. I think there's a separate viewable TOC at Google Docs, though, haven't checked and don't remember whether updated.
PPS: Forgot to mention, the MVC image processing example near the end has nice pic of Lena Söderberg! :)
Code is the best approach to understand and learn Model View Controller:
Here is a simple JS example (from Wiki)
/** Model, View, Controller */
var M = {}, V = {}, C = {};
/** Model stores data */
M.data = "hello world";
/** View controls what to present */
V.render = (M) => { alert(M.data); }
/** Controller bridges View and Model */
C.handleOnload = () => { V.render(M); }
/** Controller on Windows OnLoad event */
window.onload = C.handleOnload;
Here is a detailed post in C/C++
Model-View-Controller Explained in C++