Re: architecture OOP, Design Pattern
Victor Bazarov a ?crit :
Vincent RICHOMME wrote:
I would like your opinion about the following subject :
I have a class called CBackupSimContact that is used to copy contact
from a SIM card to the phone memory.
I have another class called CBackupDialog that is supposed to display
copy progress.
So very basically I have the following
class CBackupSimContact
{
public:
void CopyContact()
{
for (int i = 0; i < NumContacts; i++)
{
SendMessage(CONTACT_ADDED); // BAAADDD because using windows
specific mechanism
}
}
};
// MFC MACROS (BAD)
ON_MESSAGE( CONTACT_ADDED, &CBackupDialog::OnContactAdded)
class CBackupDialog
{
public:
CBackupDialog::CBackupDialog ()
{
pBackupMgr = new CBackupSimContact();
}
protected:
void OnContactAdded()
{
ProgressBar.StepIt(); // move progress bar
}
private:
ProgressBar m_ProgressBar;
CBackupSimContact* m_pBackupMgr;
};
So it's a very simple case a class doing some operations and another
that receives notifications.
For now notifications is done by a windows specific mechanism called
message and I am not satisfied with this.
What I would like to know is how could I do it in a more OO way.
I have thought of an observer pattern but don't you think it's a bit
heavy for this simple task?
No, I don't think so.
You don't have to implement the full-blown event mechanism unless you
think you can use it for other stuff around your application. I would
simply do
class CBackupSimContact {
...
template<class ContactAddedRegister>
void CopyContact(ContactAddedRegister & register)
{
for (int i = 0; i < NumContacts; i++)
{
register.OnContactAdded();
}
}
};
And then
...
CBackupSimContact pMyDoer;
CBackupDialog pDialog;
pMyDoer.CopyContact(pDialog);
V
Waou. Really interesting this solution with templates. I find it very
elegant.Now let's say the problem is more complex.
Actually my CBackupSimContact is using a thread to do its copy.
So I have :
class CBackupSimContact {
...
template<class ContactAddedRegister>
void CopyContact(ContactAddedRegister & register)
{
// Create the thread and pass this to the static method
::CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)
ThreadCopyContact,this,0,0);
}
static void ThreadCopyContact(DWORD pvParam)
{
CBackupSimContact *pThis=reinterpret_cast< CBackupSimContact
*>(pvParam);
for (int i = 0; i < NumContacts; i++)
{
?????
}
}
};
Now the solution doesn't work anymore ...