Observer模式

Observer.java

观察者

public interface Observer {
    void update(NumberGenerate numberGenerate);
}

  

DigitObserver.java

数字观察者

public class DigitObserver implements Observer {

    @Override
    public void update(NumberGenerate numberGenerate) {
        System.out.println("DigitObserver: " + numberGenerate.getNumber());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

GraphObserver.java

图像观察者

public class GraphObserver implements Observer {
    @Override
    public void update(NumberGenerate numberGenerate) {
        System.out.println("GraphObserver: ");
        int count = numberGenerate.getNumber();
        for (int i = 0; i < count; i++) {
            System.out.print("*");
        }
        System.out.println();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

NumberGenerate.java

被观察者的抽象类

public abstract class NumberGenerate {
    private List<Observer> observers = new ArrayList<>();

    public void addObserver(Observer observer) { //注册observer
        observers.add(observer);
    }

    public void deleteobserver(Observer observer) { //删除observer
        observers.remove(observer);
    }

    public void notifyObservers() { //向observer发送通知
        Iterator it = observers.iterator();
        while (it.hasNext()) {
            Observer o = (Observer) it.next();
            o.update(this);
        }

    }

    public abstract int getNumber();//获取数值

    public abstract void execute();//生成数值
}

  

RandomNumberGenerator.java

被观察者-随机数生成器

public class RandomNumberGenerator extends NumberGenerate {
    private Random random = new Random();
    private int number;

    @Override
    public int getNumber() {
        return number;
    }

    @Override
    public void execute() {
        for (int i = 0; i < 20; i++) {
            number = random.nextInt(50);
            notifyObservers();
        }
    }
}

 

Main.java 

测试类

public class Main {
    public static void main(String[] args) {
        NumberGenerate generate = new RandomNumberGenerator();
        Observer observer1 = new DigitObserver();
        Observer observer2 = new GraphObserver();
        generate.addObserver(observer1);
        generate.addObserver(observer2);
        generate.execute();
    }
}

  

运行结果:

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

posted @ 2018-07-02 09:51  KristinLee  阅读(210)  评论(0编辑  收藏  举报
jQuery火箭图标返回顶部代码