码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式

时间:2015-08-06 10:41:18      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

观察者模式的Java实现

The Observer Pattern defines a one-to-many
dependency between objects so that when one
object changes state, all of its dependents are
notified and updated automatically.

Java 的实现方式:

第一个类继承自java.util.Observable,这个类是被观察者要实现的类。实际应用中如天气预报的数据源类、监控中的数据汇总类等。这个基类有几个方法接口:

public synchronized void addObserver(Observer o)
public synchronized void deleteObserver(Observer o)
public void notifyObservers()
public void notifyObservers(Object arg)
public synchronized void deleteObservers()


protected synchronized void setChanged()

第二个类是观察者类java.util.Observer。 他只有一个方法: update

这里有几个很重要的概念需要记住:Observable类所处的角色应该是一个看板一样,想要被更新的对象要在他这里被注册(注意在整个程序中应该保持这个Observable对象的惟一性,而且有哪些观察者来订阅它完全是由主程序决定的。)Observable和Observer所共同关心的数据源应该是被独立出来的也就是update, notify中提到的arg对象

技术分享
package com.ctrip.pattern.Observer;

import java.util.Observable;
import java.util.Observer;

/**
 * Created by ygshen on 2015/8/6.
 */
public class WeatherDataSubject extends Observable {

    public WeatherDataSubject(){

    }
    public void Trigger(Object arg){
        setChanged();
        notifyObservers(arg);
    }
    @Override
    protected synchronized void setChanged() {
        super.setChanged();
    }

    @Override
    public void notifyObservers() {

        super.notifyObservers();
    }

    @Override
    public synchronized void addObserver(Observer o) {
        super.addObserver(o);
    }

    @Override
    public synchronized void deleteObserver(Observer o) {
        super.deleteObserver(o);
    }

    @Override
    public void notifyObservers(Object arg) {
        super.notifyObservers(arg);
    }

    @Override
    public synchronized void deleteObservers() {
        super.deleteObservers();
    }
}
Subject
技术分享
package com.ctrip.pattern.Observer;

import java.util.Observable;
import java.util.Observer;

/**
 * Created by ygshen on 2015/8/6.
 */
public class WeatherDataObserver implements Observer {
    private Observable _observable;

    public WeatherDataObserver(Observable subject)
    {
     _observable=subject;
        subject.addObserver(this);
    }
    @Override
    public void update(Observable o, Object arg) {

        if(o instanceof WeatherDataSubject){
            WeatherData data = (WeatherData)arg;

            System.out.print("Temprature"+data.get_temp()+"; humidity:"+data.get_humidity());
        }
    }
}
Observer
技术分享
package com.ctrip.pattern.Observer;

/**
 * Created by ygshen on 2015/8/6.
 */
public class WeatherData {
    private int _temp;
    private int _humidity;

    public int get_temp() {
        return _temp;
    }

    public void set_temp(int _temp) {
        this._temp = _temp;
    }

    public int get_humidity() {
        return _humidity;
    }

    public void set_humidity(int _humidity) {
        this._humidity = _humidity;
    }
}
观察者和被观察者都关注的Data

主程序主要负责:Observerable对象的一致性、哪些观察者要注册到被观察者中、被观察者何时触发观察者事件

技术分享
import com.ctrip.pattern.Observer.WeatherData;
import com.ctrip.pattern.Observer.WeatherDataObserver;
import com.ctrip.pattern.Observer.WeatherDataSubject;

/**
 * Created by ygshen on 2015/8/6.
 */
public class MainClass {
    public static void main(String[] args){

        WeatherDataSubject sub=new WeatherDataSubject();
        WeatherDataObserver bserver=new WeatherDataObserver(sub);
        GetSubjectorAndObservers(sub,bserver);

        WeatherData data = new WeatherData();
        data.set_humidity(123);
        data.set_temp(321);
        sub.Trigger(data);
    }


    private static void GetSubjectorAndObservers(WeatherDataSubject sub,WeatherDataObserver observer){
         sub = new WeatherDataSubject();

        observer = new WeatherDataObserver(sub);
    }
}
应用程序

观察者模式的NET实现。

 

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test.Library
{
   public class Subjector: IObservable<ObservableItem>
    {

       private List<IObserver<ObservableItem>> _observers=new List<IObserver<ObservableItem>>();

        public IDisposable Subscribe(IObserver<ObservableItem> observer)
        {
            if (!_observers.Contains(observer))
            {
                _observers.Add(observer);
            }

            return new Unsubscriber(_observers, observer);
        }

        public void Trigger(ObservableItem item) {
            foreach (var i in _observers) {
                i.OnNext(item);
            }
        }
    }

   public class Unsubscriber: IDisposable {

       private List<IObserver<ObservableItem>> _observers;
       private IObserver<ObservableItem> _observer;
       public Unsubscriber(List<IObserver<ObservableItem>> observers, IObserver<ObservableItem> observer) {
           _observers = observers;
           _observer = observer;
       }
       public void Dispose()
       {
           throw new NotImplementedException();
       }
   }

    public class ObservableItem{

    }
}
Subject

Observer:

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test.Library
{
    public class Observer : IObserver<ObservableItem>
    {
        public void OnCompleted()
        {
            throw new NotImplementedException();
        }

        public void OnError(Exception error)
        {
            throw new NotImplementedException();
        }

        public void OnNext(ObservableItem value)
        {
            Console.WriteLine("Observer is triggered");
        }
    }
}
Observer
技术分享
  public class Monitor
    {
        private void GetSubjectorAndObservers(out Subjector s, out Observer o) {
            s = new Subjector();
            o = new Observer();
            s.Subscribe(o);
        }
        public void DoMonitor(Action<Subjector> action) {
            Subjector s;
            Observer o;

            GetSubjectorAndObservers(out s, out o);
            s.Trigger(new ObservableItem());
            action(s);
        }
    }


 static void Main(string[] args)
        {
            Monitor mon = new Monitor();
            mon.DoMonitor((observer) =>
            {
                Console.WriteLine("Hello world");
            });
        }
主程序

 


 

设计模式

标签:

原文地址:http://www.cnblogs.com/ygshen/p/4707144.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!