Java的观察者

class Teacher extends  Observable
{
    public void startLesson()
    {
        System.out.println(String.format("老师说开始上课"));
        super.setChanged();
        super.notifyObservers();
    }
}

class Student implements Observer
{
    private String name;
    public Student(String name)
    {
        this.name=name;
    }
    @Override
    public void update(Observable o, Object arg)
    {
        System.out.println(String.format("Name:%s起立",name));
    }
    public String getName()
    {
        return name;
    }
}
public static void main(String[] args) {
       
        Teacher sir=new Teacher();
        sir.addObserver(new Student("Grace") );
        sir.addObserver(new Student("Aven") );
        sir.startLesson();
}

 

posted @ 2017-03-16 17:33  zslm___  阅读(159)  评论(0编辑  收藏  举报