设计模式之管理状态-观察者模式

十七 observer观察者 通知状态变化

public interface Observer {
    public abstract void update(NumberGenerator generator);
}

public abstract class NumberGenerator {
    private Vector observers=new Vector();
    public void addObserver(Observer observer){
        observers.add(observer);
    }
    public void notifyObservers(){
        Iterator iterator = observers.iterator();
        while (iterator.hasNext()){
            Observer observer=(Observer) iterator.next();
            observer.update(this);
        }
    }
    public abstract int getNumber();
    public abstract void execute();
}

public class GraphObserver implements Observer {
    @Override
    public void update(NumberGenerator generator) {
        System.out.println("GraphObserver :");
        int number = generator.getNumber();
        for (int i = 0; i < number; i++) {
            System.out.print("*");
        }
        System.out.println("");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class DigitObserver implements Observer {
    @Override
    public void update(NumberGenerator generator) {
        System.out.println("DigitObserver:"+generator.getNumber());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class RandomNumberGenerator extends NumberGenerator {
    private Random random=new Random();
    private int number;
    @Override
    public int getNumber() {
        return number;
    }

    @Override
    public void execute() {
        for (int i = 0; i < 10; i++) {
            number=random.nextInt(50);
            notifyObservers();
        }
    }
}
public class Test {
    public static void main(String[] args) {
        NumberGenerator numberGenerator=new RandomNumberGenerator();
        Observer observer1=new DigitObserver();
        Observer observer2=new GraphObserver();
        numberGenerator.addObserver(observer1);
        numberGenerator.addObserver(observer2);
        numberGenerator.execute();
    }

}

你可能感兴趣的:(设计模式)