[英]C++: Single instance of a dialog?
我有一個我只想存在一次的對話框,因為兩個不同的類(MainFrame,可以直接打開它,Wizard,可以使用從向導本身引入的設置打開它)必須在任何給定時間訪問它。 理想情況下,我希望用戶能夠使用向導打開對話框,填寫所有內容,然后關閉它。 如果他們需要更改設置,他們應該能夠使用 MainFrame 打開它並在那里進行編輯。
我實現它的方式目前有兩個不同的對話框實例。 如果它是在向導之后從 MainFrame 打開的,則 Mainframe 一號將具有默認值,而向導一號也可以使用向導中的值打開。
我嘗試在此之后實施 singleton 設計模式,但嘗試打開向導或對話框本身會導致它給出 xC0000005 錯誤。
MainFrame 可以訪問 Wizard 和 Dialog 標頭,Dialog 可以訪問 Wizard header 用於將數據從 Wizard 傳遞到 Dialog 的 function(在 Wizard 的標頭中前向聲明 Dialog)。
我真的不確定 go 前進的方式,但感謝任何幫助。 如有必要,我可以提供有關我的實現的代碼。
編輯:在鏈接的 URL 之外沒有做太多事情,但是如果這有什么不同的話,它是在 wxWidgets 上開發的。 這是相關代碼。
Dialog.h
#include "Wizard.h"
class Dialog
{
private:
Dialog() {}
Dialog(Dialog const& copy) {}
Dialog& operator=(Dialog const& copy) {}
static Dialog* instance;
//many functions and variables
public:
Dialog(wxWindow* parent) //more fields, generated by wxFormBuilder
~Dialog();
Wizard* wizard;
void SetRelative(Wizard* inWizard);
static Dialog* GetInstance()
{
instance = new Dialog(NULL);
return instance;
}
};
Dialog.cpp
#include "Dialog.h"
Dialog* Dialog::instance = 0;
Dialog::Dialog(wxWindow parent, etc.)
{
//lots of stuff
}
//event handlers, helper functions
void Dialog::SetRelative(Wizard* inWizard)
{
this->Wizard = inWizard
}
Wizard.h
class Dialog;
class Wizard
{
public:
Dialog* dialog;
}
Wizard.cpp
#include "WizardSetup.h"
#include "WizardDialog.h"
Wizard::Wizard(wxWindow* parent, etc.)
{
//bunch of stuff
dialog->GetInstance()
dialog->SetRelative(this) <--------- hangs at this statement
}
MainFrame.cpp
#include "Dialog.h"
#include "Wizard.h"
class MainFrame: public wxFrame
{
protected:
Dialog* m_dialog;
Wizard* m_wizard;
etc.
}
MainFrame.cpp
#include "MainFrame.h"
MainFrame::MainFrame(wxWindow* parent, etc.)
{
//stuff here
m_dialog->GetInstance();
}
void MainFrame::menuDialogOnMenuSelection( wxCommandEvent& event)
{
m_dialog->Show(); <-------- hangs here
}
此代碼的三個(直接)問題:
您的Dialog::Dialog(WxWindow*)
構造函數是公開的,它發送關於 singleton object 的性質的混合信號。 雖然不直接對崩潰或掛起負責,但當 Next Guy(可能是您在月)嘗試維護此代碼。
您沒有在Dialog::GetInstance()
function 中檢查是否存在已實例化的Dialog
。 你應該有
static Dialog* GetInstance()
{
if (instance == nullptr) instance = new Dialog(nullptr);
return instance;
}
Dialog*
成員變量(例如Wizard::dialog
和MainFrame::m_dialog
)分配給 singleton Dialog
的地址。 一定要這樣做:// (in the Wizard constructor for example)
dialog = Dialog::GetInstance();
附錄說明:我認為值得一提的是,singleton 模式通常被稱為反模式。 我不夠聰明,無法理解為什么。 據推測,它往往會導致一些不良的編碼實踐,而且有時處理起來肯定很麻煩,但是,嘿,不管工作如何完成。 請記住,根據 Some People 的說法,它不一定是工作的最佳工具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.