Chinaunix首页 | 论坛 | 博客
  • 博客访问: 458505
  • 博文数量: 711
  • 博客积分: 3000
  • 博客等级: 中校
  • 技术积分: 4200
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-28 14:18
文章分类

全部博文(711)

文章存档

2011年(1)

2008年(710)

我的朋友

分类:

2008-10-28 14:19:40

    1  Observable类用于跟踪那些当发生一个改变时希望收到通知的所有个体——无论“状态”是否改变。如果有人说“好了,所有人都要检查自己,并可能要进行更新”,那么Observable类会执行这个任务——为列表中的每个“人”都调用notifyObservers()方法。notifyObservers()方法属于基础类Observable的一部分。

    2  Observable对象会自动调用每个Observer对象的update()方法。

    3  为真正产生效果,必须从Observable继承,并在衍生类代码的某个地方调用setChanged()。这个方法需要设置“changed”(已改变)标志,它意味着当调用notifyObservers()的时候,所有观察器事实上都会收到通知。

    4  通过notifyObservers()和update()中的代码的结合,可以应付一些非常复杂的局面。


    view plaincopy to clipboardprint?
    import java.awt.*;

    import java.awt.event.*;

    import java.util.*;

 

    // You must inherit a new type of Observable:

    class BoxObservable extends Observable {

      public void notifyObservers(Object b) {

        // Otherwise it won't propagate changes:

        setChanged();

        super.notifyObservers(b);

      }

    }

 

    public class BoxObserver extends Frame {

      Observable notifier = new BoxObservable();

      public BoxObserver(int grid) {

        setTitle("Demonstrates Observer pattern");

        setLayout(new GridLayout(grid, grid));

        for(int x = 0; x < grid; x++)

          for(int y = 0; y < grid; y++)

            add(new OCBox(x, y, notifier));

      }

      public static void main(String[] args) {

        int grid = 8;

        if(args.length > 0)

          grid = Integer.parseInt(args[0]);

        Frame f = new BoxObserver(grid);

        f.setSize(500, 400);

        f.setVisible(true);

        f.addWindowListener(

          new WindowAdapter() {

            public void windowClosing(WindowEvent e) {

              System.exit(0);

            }

          });

      }

    }

 

    class OCBox extends Canvas implements Observer {

      Observable notifier;

      int x, y; // Locations in grid

      Color cColor = newColor();

      static final Color[] colors = {

        Color.black, Color.blue, Color.cyan,

        Color.darkGray, Color.gray, Color.green,

        Color.lightGray, Color.magenta,

        Color.orange, Color.pink, Color.red,

        Color.white, Color.yellow

      };

      static final Color newColor() {

        return colors[

          (int)(Math.random() * colors.length)

        ];

      }

      OCBox(int x, int y, Observable notifier) {

        this.x = x;

        this.y = y;

        notifier.addObserver(this);

        this.notifier = notifier;

        addMouseListener(new ML());

      }

 

[1]   

【责编:landy】

--------------------next---------------------

阅读(257) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~