observe

package observe;

public class Boss
{
private int status = 1;//0为老板出去,1为老板进来

public int getStatus()
{
return status;
}

public void setStatus(int status)
{
this.status = status;
}


}



package observe;

public interface Staff
{
public void goodBehave();
public void badBehave();
}



package observe;

public class StaffA implements Staff
{

public void goodBehave()
{
System.out.println("StaffA好好工作!");
}

public void badBehave()
{
System.out.println("StaffA打Dota");
}

}


package observe;

public class StaffB implements Staff
{

public void goodBehave()
{
System.out.println("StaffB好好工作!");
}

public void badBehave()
{
System.out.println("StaffB看NBA!");
}

}



package observe;

import java.util.ArrayList;
import java.util.List;

public class Proscenium
{
private Boss boss;
private List<Staff> staffs;//可以自己决定通知那些员工

public void addStaff(Staff staff)
{
staffs.add(staff);
}
public void delStaff(Staff staff)
{
staffs.remove(staff);
}

public Proscenium()
{
boss = new Boss();
staffs = new ArrayList<Staff>();
}

public void notice()
{
int status = boss.getStatus();
if(staffs.size()<=0)
{
return;
}
if( status == 1)//1老板来了 全部认真工作
{
System.out.println("老板来了,请注意.....");
for (Staff staff : staffs)
{
staff.goodBehave();
}
boss.setStatus(0);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
notice();//自己调用下自己,改变boss的状态。其实用线程好控制些
}else {//全部做自己想做做出事
System.out.println("老板走了,请随意....");
for (Staff staff : staffs)
{
staff.badBehave();
}
}
}
}



package observe;

public class Test {

public static void main(String[] args)
{
Proscenium proscenium = new Proscenium();
proscenium.addStaff(new StaffA());
proscenium.addStaff(new StaffB());
proscenium.notice();
}

}
/**
* 观察者模式:一个对象proscenium监视着一个对象boss,boss放生一丁点变化后,proscenium就会
* 通知其他关联的对象staff做相应的操作,一对多操作
*/

你可能感兴趣的:(observe)