📄 observerdesignpatt.cpp
字号:
/*
BE Comp H
Title:Observer Design Pattern
*/
#include <iostream.h>
#include<conio.h>
#include<string.h>
static int i;
class Subject {
int a,b;
public:
void setVal( int x,int y )
{
a=x;
b=y;
notify();
}
int getVal_a()
{
return a;
}
int getVal_b()
{
return b;
}
void notify();
};
Subject s;
class Observer
{ protected:
int x,y;
public:
void update(int e,int f)
{
x=e;
y=f;
}
};
class AddObserver : public Observer
{
public:
void display()
{
cout<<"\nThe Addition is:"<<x+y;
}
};
class MulObserver : public Observer
{
public:
void display()
{
cout<<"\nThe Multiplication is:"<<x*y;
}
};
AddObserver ad;
MulObserver ml;
void Subject::notify()
{
ad.update(s.getVal_a(),s.getVal_b());
ml.update(s.getVal_a(),s.getVal_b());
}
void main( void )
{
int a,b;
char ch;
clrscr();
do
{
cout<<"\nEnter value for a and b\n";
cin>>a>>b;
s.setVal(a,b);
ad.display();
ml.display();
cout<<"\n\nChange a and b? ";
ch=getche();
}while(ch=='y'||ch=='Y');
getch();
}
/*
Enter value for a and b
5
6
The Addition is:11
The Multiplication is:30
Change a and b? y
Enter value for a and b
7
8
The Addition is:15
The Multiplication is:56
Change a and b? y
Enter value for a and b
8
9
The Addition is:17
The Multiplication is:72
Change a and b?
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -