//在软件的构建过程中,我们需要为某些对象建立一种通知依赖关系--一个对象(目标对象)发生改变
//所有的依赖对象(观察者对象)都将得到通知,如果依赖关系过于紧密,将使软件不能很好的抵御变化
//使用面向对象,可以将这种关系弱化,并形成稳定依赖关系,从而实现软件体系结构的松耦合
class MainForm:public Form,public IProgress
{
TextBox *textFilePath;
TextBox *textFileNumber;
ProgressBar* progressBar;
ConsoleNotifier cn;
public:
Button1_Click() {
string filePath = textFilePath->getText();
int number = atoi(textFileNumber->getText().c_str());
FileSplitter splitter(filepath, number, this);//单个观察者
splitter.addIProgress(this);//支持多个观察者 订阅通知
splitter.addIProgress(&cn);
splitter.split();
splitter.removeIProgress(this);
}
virtual void DoProgress(float value) {
progressBar->setvalue(value);
}
};
class ConsoleNotifier :public IProgress
{
virtual void DoProgress(float value)
{
cout << ".";
}
};
class IProgress {
public:
virtual void DoProgress(float value) = 0;
virtual ~IProgress() {}
};
class FileSplitter
{
string m_filePath;
int m_fileNumber;
//ProgressBar *m_progressBar; //通知控件 紧耦合->松耦合 本文件不依赖界面控件,仅仅是一个抽象接口
IProgress* m_iprogress; //抽象通知机制
vector<IProgress*>m_iprogresslist;//支持多个观察者
public:
FileSplitter(const string& filePath, int fileNumber, IProgress*iprogress) :
m_filePath(filePath),
m_fileNumber(m_fileNumber),
m_iprogress(iprogress)
{
}
void add_IProgress(IProgress*iprogress)//多个观察者
{
m_iprogresslist.pushback(iprogress);
}
void remove_IProgress(IProgress*iprogress) //多个观察者
{
m_iprogresslist.remove(iprogress);
}
void splitter() {
for (int i = 0; i < m_fileNumber; i++)
{
//...
float progressValue = m_fileNumber;
progressValue = (i + 1) / progressValue;
//m_progressBar->setValue((i + 1) / m_fileNumber);
onProgress(progressValue);
}
}
protected:
virtual void onProgress(float value) {
if (m_iprogress != nullptr)
{
m_iprogress->DoProgress(progressValue);
}
}
virtual void onProgress(float value) { //多个观察者
List<IProgress*>::Iterator itor = m_iprogress.beigin();
while (itor != m_iprogress.end)
{
(*itor)->Doprogress(value);
itor++;
}
}
};
观察者模式
最新推荐文章于 2024-03-27 10:22:08 发布