觀察者模式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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章