观察者模式【OBSERVER PATTERN】


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

  public class DigitObserver implements Observer {
     public void update(NumberGenerator generator) {
         System.out.println("DigitObserver:" + generator.getNumber());
         try {
             Thread.sleep(100);
         } catch (InterruptedException e) {
         }
     }
 }

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

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

  public class RandomNumberGenerator extends NumberGenerator {
     private Random random = new Random();   
     private int number;                    
     public int getNumber() {                
         return number;
     }
     public void execute() {
         for (int i = 0; i < 20; i++) {
             number = random.nextInt(50);
             notifyObservers();
         }
     }
 }

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

你可能感兴趣的:(java,thread)