`

者_察_观

 
阅读更多
/**
* 被观察者对象
*/
public class Observable
{
    private boolean chanaged = false;
   
    private Vector<Object> obs;
   
    public Observable()
    {
        obs = new Vector<Object>();//创建一个同步列表,保存所有的观察者
    }
   
    public void chuangge()
    {
        System.out.println("选手“aaa”开始唱歌..."); //$NON-NLS-1$
    }
   
    /**
     * 添加观察者到列表中
     * @param o
     */
    public synchronized void add(Observer o)
    {
        if (o != null)
        {
            if (!obs.contains(o))
            {
                obs.addElement(o);
            }
        }
    }
   
    /**
     * 通知操作,传递一个参数到观察者那里,进行操作
     * @param obj
     */
    public void notifyObservers(Object obj)
    {
        Object[] arrayLocal = obs.toArray();
        for (int i = arrayLocal.length - 1; i >= 0; i--)
        {
            Object object = arrayLocal[i];
            if (object instanceof Observer)
            {
                Observer os = (Observer)object;
                os.update("sss");
            }
        }
    }
   
    public static void main(String[] args)
    {
        Observable observable = new Observable();
       
        ObsInstance1 obsInstance1 = new ObsInstance1();
        ObsInstance2 obsInstance2 = new ObsInstance2();
       
        observable.add(obsInstance1);
        observable.add(obsInstance2);
       
        observable.chuangge();
    }
}

/**
* 观察者接口
*/
interface Observer
{
    public int update(Object obj);
}
/**
* 观察者一
*/
public class ObsInstance1 implements Observer
{
    @Override
    public int update(Object obj)
    {
        System.out.println("评委一,你唱的太难听了。。。"); //$NON-NLS-1$
        return 60;
    }
}
/**
* 观察者二
*/
public class ObsInstance2 implements Observer
{
    @Override
    public int update(Object obj)
    {
        System.out.println("评委二,你长的太丑了。。。"); //$NON-NLS-1$
        return 61;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics