我有一系列的問題需要在創建GUI時將問題與邏輯分離。
以下是一個簡單對話框的簡單例子,該對話框使用「Humble Dialog」方法具有標籤和按鈕。按下按鈕應該在標籤上顯示一些文字。我已經使用了C++,我很喜歡Qt,但我想它可以被所有其他讀者閱讀。
在任何情況下,我都對可能因爲語言的選擇而產生的副作用感興趣(我正在使用C++來引入此項目)。爲「低級對話框」創建視圖的方法
class IView {
public:
IView(){}
virtual ~IView(){}
virtual void showResult(const QString &text)=0;
};
class Presenter {
public:
Presenter(IView *view){
m_View = view;
}
~Presenter(){}
void buttonPressed(){
QString text;
// Evaluate text
m_View->showResult(text);
}
private:
IView *m_View;
}
// Multiple inheritance. Is this OK?
class MyView : public QDialog, public IView {
public:
MyView(){
m_Presenter = new Presenter(this);
m_Button = new QPushbutton(this);
m_Label = new QLabel(this);
// Ui event handled inside view but then directly
// propagated to the Presenter
connect(m_Button,SIGNAL(clicked()),this,SLOT(buttonPressed()));
}
~MyView(){
delete m_Presenter;
// Qt will automatically delete m_Button and m_Label;
}
void showResult(const QString &text){
m_Label->setText(text);
}
protected slots:
void buttonPressed(){
m_Presenter->buttonPressed();
}
private:
Presenter *m_Presenter;
QPushbutton *m_Button;
QLabel *m_Label;
}
class TestView : public IView {
public:
TestView(){}
~TestView(){}
void showResult(const QString &text){
m_LabelText = text;
}
QString getResult(){
return m_LabelText;
}
private:
QString m_LabelText;
}
// Test code
TestView view;
Presenter presenter(&view);
presenter.buttonPressed();
EXPECT_EQ(view.getResult(),"Expected Result");
// Procuction code
MyView view;
view.show();
現在這就是我通過遵循initial work on the Humble dialog by Feathers得到的。我從Fowler's implentation得到的方法是避免在MyView的構造函數中創建Presenter類的實例,而是將其作爲參數傳遞,以便生成代碼看起來像測試代碼。我個人喜歡我在這裏介紹的方法。
所以,
- 打算把它與多重繼承(見我的MyView的類註釋)一起使用?
- 應該將事件直接傳播給演示者還是應該在視圖中處理,以便調用相應的演示者動作(正如我在此處所做的,以避免必須使演示者成爲QObject才能處理UI事件)?
- 還有其他的評論嗎?
QString支持Unicode。只要您的字符串中沒有任何字符串具有Unicode字符,您爲轉換支付的所有費用就會有一點表現。 – 2008-10-29 10:20:22