标签: observer-pattern

如何在Observer中处理数据输出?

我有一个Observable和一个Observer.observable会在后台线程中下载一些东西并调用notifyObservers让观察者读取状态.

在某些时候,public void update观察者试图更新GUI

((TextView)findViewById('R.id.foo')).setText("bar");
Run Code Online (Sandbox Code Playgroud)

但似乎可观察线程调用此方法,因为Observable(!!!)抛出这个:

 android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
 at android.view.ViewRoot.checkThread(ViewRoot.java:2462)
 at android.view.ViewRoot.requestLayout(ViewRoot.java:512)
 ...
 at com.mynamespace.acitivty.TrackActivity.startPlay(TrackActivity.java:72)
 at com.mynamespace.acitivty.TrackActivity.update(TrackActivity.java:107)
 at java.util.Observable.notifyObservers(Observable.java:147)
 at java.util.Observable.notifyObservers(Observable.java:128)
 at com.mynamespace.module.communication.Download.stateChanged(Download.java:213)
 at com.mynamespace.module.communication.Download.run(Download.java:186)
 at java.lang.Thread.run(Thread.java:1058)
Run Code Online (Sandbox Code Playgroud)

有什么办法可以防止这种情况发生吗?我确定我在这里遗漏了一些明显的东西.

java multithreading android exception observer-pattern

1
推荐指数
1
解决办法
792
查看次数

观察者模式的单元测试

我对软件测试很新.我想知道对观察者模式进行单元测试的正确方法是什么?例如,如果我们实现了以下4个类:主题类(attach/detach/notify),Observer接口类(update virtual method),ConcreteSubject类和ConcreteObserver(具体更新方法).如何为每个类编写测试轨道?有什么好的例子可以参考吗?

谢谢你的任何投入.

unit-testing design-patterns observer-pattern

1
推荐指数
1
解决办法
5064
查看次数

1
推荐指数
1
解决办法
103
查看次数

在构造函数中泄漏这个

这个Controller类是一个单身人士,这似乎是一个允许安全传递this到的特殊情况Controller.

Netbeans给出了

配置"在构造函数中传递可疑参数"提示

对于controller.addObserver(this);这点让我问更好的方法是什么,虽然我收集这不是一个好方法.

package net.bounceme.dur.usenet.swing;

import java.util.Observable;
import java.util.Observer;
import java.util.logging.Logger;
import javax.mail.Folder;
import javax.swing.ListModel;
import net.bounceme.dur.usenet.controller.Controller;
import net.bounceme.dur.usenet.controller.MessageBean;
import net.bounceme.dur.usenet.controller.MessagesDefaultListModel;

public class MessageSelect extends javax.swing.JPanel implements Observer {

    private static final Logger LOG = Logger.getLogger(MessageSelect.class.getName());
    private Controller controller = Controller.getInstance();
    private ListModel messages = new MessagesDefaultListModel();
    private MessageBean messageBean = new MessageBean();

    @SuppressWarnings("unchecked")
    public MessageSelect() {
        controller.addObserver(this);
        initComponents();
        messagesJList.setPrototypeCellValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    }
Run Code Online (Sandbox Code Playgroud)

java memory-management observable observer-pattern

1
推荐指数
1
解决办法
2882
查看次数

KVO不适用于com.alpha之类的键路径。

我的NSMutableDictionary包含简单键(@“一个”,@“两个”,@“三个”)和复杂键(@“ com.alpha”,@“ com.beta”)。是否可以将观察者用于复杂的键?

观察者使用简单的键可以很好地工作,但是不能使用复杂的键。有什么解决办法?

[self.dict addObserver:self forKeyPath:@"com.alpha" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];

-(IBAction) onChange:(id)sender
{
 [self.dict setObject:@"newValue" forKey:@"com.alpha"];
}

-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
  NSLog(@"____ value had changed");
}
Run Code Online (Sandbox Code Playgroud)

key-value-observing ios observer-pattern

1
推荐指数
1
解决办法
800
查看次数

调用函数与调度事件

当你可以直接调用函数时,创建自己的事件有什么用呢?

例如

var customEvent:Event = new Event("ev");
_myObject.addEventListener("ev", handler);

private function handler(e:Event):void
{
    //Do something
}

//And then dispatching the event else where like this
_myObject.dispatchEvent(customEvent);
Run Code Online (Sandbox Code Playgroud)

当你可以像这样直接调用函数

handler();
private function handler():void
{
//do something
}
Run Code Online (Sandbox Code Playgroud)

自定义事件究竟是什么意思?在这种情况下,我应该使用哪一个来提高效率和减少资源消耗?

oop events design-patterns actionscript-3 observer-pattern

1
推荐指数
1
解决办法
482
查看次数

Observable不响应阻塞集合在不同的线程上发生了变化

我有以下代码:

class Program
{
    static void Main(string[] args)
    {
        var watcher = new SNotifier(DumpToConsole);
        watcher.StartQueue();

        Console.ReadLine();
    }

    private static void DumpToConsole(IList<Timestamped<int>> currentCol)
    {
        Console.WriteLine("buffer time elapsed, current collection contents is: {0} items.", currentCol.Count);
        Console.WriteLine("holder has: {0}", currentCol.Count);
    }
}
Run Code Online (Sandbox Code Playgroud)

SNotifier:

public class SNotifier
{
    private BlockingCollection<int> _holderQueue;
    private readonly Action<IList<Timestamped<int>>> _dumpAction;

    public SNotifier(Action<IList<Timestamped<int>>> dumpAction)
    {
        PopulateListWithStartValues();
        _dumpAction = dumpAction;
    }

    public void StartQueue()
    {
        PopulateQueueOnDiffThread();

        var observableCollection = _holderQueue.ToObservable();

        var myCollectionTimestamped = observableCollection.Timestamp();
        var bufferedTimestampedCollection = myCollectionTimestamped.Buffer(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3));

        using (bufferedTimestampedCollection.Subscribe(_dumpAction)) …
Run Code Online (Sandbox Code Playgroud)

c# multithreading system.reactive observer-pattern

1
推荐指数
1
解决办法
690
查看次数

为什么Observable是一个类而Observer是一个接口?

我对Model-View-Controller的东西还算是新手,这让我很不高兴。为什么Observable类是要扩展的类而Observer类是接口?这样做的目的是什么?

java model-view-controller observer-pattern

1
推荐指数
1
解决办法
1568
查看次数

使用装饰器在 Python3 中实现观察者模式

这个问题一般与观察者模式无关。它专注于在该模式中使用装饰器。该问题基于类似问题的答案

#!/usr/bin/env python3

class Observable:
    """
        The object that need to be observed. Alternative names are 'Subject'.
        In the most cases it is a data object.
    """
    def __init__(self):
        self._observers = []

    def register_observer(self, callback):
        self._observers.append(callback)
        return callback

    def _broadcast_observers(self, *args, **kwargs):
        for callback in self._observers:
            callback(*args, **kwargs)


class TheData(Observable):
    """
        Example of a data class just for demonstration.
    """
    def __init__(self, data):
        Observable.__init__(self)
        self._data = data

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, data):
        self._data = …
Run Code Online (Sandbox Code Playgroud)

python python-3.x observer-pattern python-decorators

1
推荐指数
1
解决办法
3349
查看次数

多个主体调用一个观察者的观察者模式

我正在尝试在java. 有了这个,我想要一个listenerfor 当 a Goomba(马里奥中的主要敌人)被杀死时。经过一番研究,我查看了Observer Pattern

我做的 interface

public interface GoombaDeathListener {
    void onGoombaDeath(Goomba goomba);
}
Run Code Online (Sandbox Code Playgroud)

接下来,我自己做了一个classPlayer

public class Player extends Entity implements GoombaDeathListener {
    @Override
    public void onGoombaDeath(Goomba goomba) {. . .}
}
Run Code Online (Sandbox Code Playgroud)

我也做了一个 Goomba class

public class Goomba extends Entity {
    ArrayList<GoombaDeathListener> deathListeners = new ArrayList<>();

    public void onDeath() {
        for (GoombaDeathListener listener : deathListeners) {
            listener.onGoombaDeath(this);  
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我相信(不知道如果我在这个充分理解),这使Goombaobserver,我想不止一个Goomba,这意味着我不得不多ArrayLists的 …

java observer-pattern

1
推荐指数
1
解决办法
1911
查看次数