java设计模式-观察者模式

一个动作,会产生另一个动作

观察者模式的组件如下

1. 被观察者接口(add, remove, notification)

2.观察者接口(update)

3.被观察者实例(1个)

4.观察者实例(多个)

/**
 * 被观察者的接口
 * @author ietown
 *
 */
public interface IWatched {

    public void add(IWatcher IWatcher);
    
    public void remove(IWatcher IWatcher);
    
    public void notification(String content);
}

/**
 * 观察者接口
 * @author ietown
 *
 */
public interface IWatcher {

    public void update(String content);
}

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

/**
 * 被观察的小明同学
 * @author ietown
 *
 */
public class XiaoMing implements IWatched{

    private List<IWatcher> wathcerList = new ArrayList<IWatcher>();
    
    /*
     * 小明的踢球行为被观察,通过this.tell()
     */
    public void playFootBall() {
        System.out.println("小明踢足球");
        this.notification("踢足球");
    }
    
    /*
     * 小明的回家行为被观察,通过this.tell()
     */
    public void comeback() {
        System.out.println("小明回家");
        this.notification("回家");
    }
    
    @Override
    public void add(IWatcher watcher) {
        wathcerList.add(watcher);
    }

    @Override
    public void remove(IWatcher IWatcher) {
        wathcerList.remove(IWatcher);
    }

    /**
     * 这里通知所有的观察者,通过调用观察者的update()方法
     */
    @Override
    public void notification(String content) {
        for(IWatcher watcher : wathcerList) {
            watcher.update(content);
        }
    }
    
}

/**
 * 观察者:老师
 * @author ietown
 *
 */
public class Teacher implements IWatcher{

    /**
     * 该方法将会在被观察者的notification方法中被调用
     */
    @Override
    public void update(String content) {
        this.tearcherLook(content);
    }
    
    private void tearcherLook(String content) {
            System.out.println("老师监视小明");
            System.out.println("小明正在:" + content);
    }

}

/**
 * 观察者:妈妈
 * @author ietown
 *
 */
public class Mother implements IWatcher{

    /**
     * 该方法将会在被观察者的notification方法中被调用
     */
    @Override
    public void update(String content) {
        this.MotherLook(content);
    }
    
    private void MotherLook(String content) {
            System.out.println("妈妈关注小明");
            System.out.println("小明正在:" + content);
    }

}

public class Main {

    public static void main(String[] args) {
        XiaoMing xiaoMing = new XiaoMing();
        
        IWatcher teacher = new Teacher();
        IWatcher mother = new Mother();
        
        xiaoMing.add(teacher); // 添加观察者老师
        xiaoMing.add(mother); // 添加观察者妈妈
        
        xiaoMing.playFootBall(); // 小明的动作
        xiaoMing.comeback(); // 小明的动作
    }
}


你可能感兴趣的:(java)