According to my understanding, to reduce the coupling between classes, try to avoid dealing with them directly.
Or, correctly, two classes with clear division of labor should manage their own things separately, instead of"Inquire"Other things.
For example:
The requirement is as follows:
When a class updates data, you need to send an email to the relevant personnel.
Code 1:
Public dataaccess ()
{
//
// Todo: add the constructor logic here
//
}
Public void updatedata (data)
{
//
// Directly initialize the mymail class and call the mail method.
// Use mail Notification after data is updated
New mymail (). Sendmail (Mail );
}
}
Public class mymail
{
Public mymail ()
{
}
Public void Sendmail (mailargs ex)
{
}
}
Code 2
A special event class is defined to accept the trigger events for the data processing class and send emails in the event class.
As a data update class, data is only updated.
It is handled by an intermediate class.
Public class dataaccess
{
Protected eventclass E;
Public dataaccess ()
{
//
// Todo: add the constructor logic here
//
E = new eventclass (this );
}
Public void updatedata (data)
{
//
// Use Event Notification
If (updateevent! = NULL)
Updateevent (this );
}
Define events # region define events
Public Delegate void updateeventhandler (Object sender );
Public event updateeventhandler updateevent;
# Endregion
}
Public class eventclass
{
Public eventclass (dataaccess)
{
A. updateevent + = new maid. hr. biz. dataaccess. updateeventhandler (a_updateevent );
}
Private void a_updateevent (Object sender)
{
New mymail (). Sendmail (Ex );
}
}
Public class mymail
{
Public mymail ()
{
}
Public void Sendmail (mailargs ex)
{
}
}
}