观察者模式C++版---铃声

#include<iostream>
#include<cstdio> 
#include<algorithm>
#include<string>
#include<list>
#include<cstdlib>
using namespace std;
struct Observe
{
 string student;
 string teacher;
};

struct list<Observe>observers;
list<Observe>::iterator i;
    
     

void ConcreteObserve1(Observe& a,int x)   
{  if(x==1)
    a.student="学生进入教室";
    else
     a.student="学生放学";
}  
void ConcreteObserve2(Observe& b,int x)   
{  if(x==1)
    b.teacher="老师上课";
    else
    b.teacher="老师下课";
}  

void ConcreteSubject(int x)
{   if(x==1)
{
    cout<<"上课铃声响"<<endl; 
        cout<<"-----------"<<endl;
}
else
{
    cout<<"下课铃声响"<<endl; 
        cout<<"-----------"<<endl;
}
    
    for (i = observers.begin(); i != observers.end(); ++i) {
    
       cout<<i->student<<endl;
      cout<<i->teacher<<endl;
       
    }
}


int main(){
    for(int t=0;t<10;t++){
        int x= rand()%2;
   cout<<x<<endl;
    Observe Observer1;
    Observe Observer2;
  ConcreteObserve1(Observer1,x) ;
  ConcreteObserve2(Observer2,x) ;
  
 observers.push_front(Observer1);
 observers.push_front(Observer2) ;
 
 ConcreteSubject(x);
    }
   
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/caiyu5/p/9648483.html