观察者模式Java-使用线程的多个观察者

问题描述 投票:4回答:2

我正在尝试学习所有主要的设计模式。我刚刚开始学习Java中的多线程。这是观察者模式代码,其中有多个观察者,可观察对象在while true循环中运行。我遇到以下两个问题:

  1. 调用notifyObservers时,即使观察者正在访问可观察值的获取器,我也必须将新值传递给它。如果我不这样做,那么观察者获取/打印的值为null。我创建了一个setter函数来演示它。
  2. 我创建了两个观察者,显然两个的大多数代码都是相似的。我不确定如何在不复制代码的情况下实现新观察者或创建观察者列表。我创建了basicObserver并尝试在MyObserver3中继承它,但是我不确定如何实现它。

    import java.util.Observable;
    import java.util.Observer;
    
    public class ObserverPatternMultipleObserversUsingThreads
    {
        public static void main(String[] args)
        {
            ObservableValue observableObj = new ObservableValue(10);
    
            MyObserver1 observer1 = new MyObserver1(observableObj);
            MyObserver2 observer2 = new MyObserver2(observableObj);
            MyObserver3 observer3 = new MyObserver3(observableObj);
    
            observableObj.addObserver(observer1);
            observableObj.addObserver(observer2);
    
            observableObj.start();
    
            System.out.println("Calling Listeners");
    
            observer1.printObservablesValue();
            observer2.printObservablesValue();
    
            System.out.println("Main thread says: Sleeping for 3 second(s)");
    
            try
            {
                Thread.sleep(3000);
            }
    
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
    
            System.out.println("Main thread says: Going to change Observables Value");
    
            observableObj.setValue(20);
        }
    }
    
    class basicObserver
    {
        private ObservableValue obsValObj = null;
    
        public basicObserver(ObservableValue obsVal)
        {
            this.obsValObj = obsVal;
        }
    
        public void printObservablesValue()
        {
            System.out.println("Observer says: [" + obsValObj.getValue() + "]");    
        }
    
        public void update(Observable o, Object arg)
        {
            Integer count = (Integer) arg;
            System.out.println("Observer says: Value changed to: [" + count + "]");
        }
    }
    
    class MyObserver3 extends basicObserver implements Observer
    {
        public MyObserver3(ObservableValue obsVal)
        {
            super(obsVal);
        }
    }
    
    class MyObserver1 implements Observer
    {
        private ObservableValue obsValObj = null;
    
        public MyObserver1(ObservableValue obsVal)
        {
            this.obsValObj = obsVal;
        }
    
        public void printObservablesValue()
        {
            System.out.println("MyObserver1 says: [" + obsValObj.getValue() + "]"); 
        }
    
        public void update(Observable o, Object arg)
        {
            Integer count = (Integer) arg;
            System.out.println("MyObserver1 says: Value changed to: [" + count + "]");
        }
    }
    
    class MyObserver2 implements Observer
    {
        private ObservableValue obsValObj = null;
    
        public MyObserver2(ObservableValue obsVal)
        {
            this.obsValObj = obsVal;
        }
    
        public void printObservablesValue()
        {
            System.out.println("MyObserver2 says: [" + obsValObj.getValue() + "]"); 
        }
    
        public void update(Observable o, Object arg)
        {
            Integer count = (Integer) arg;
            System.out.println("MyObserver2 says: Value changed to: [" + count + "]");
        }
    }
    
    class ObservableValue extends Observable implements Runnable
    {
        private int n = 0;
    
        public ObservableValue(int x)
        {
            this.n = x;
        }
    
        public int getValue()
        {
            return n;
        }
    
        public void setValue(int x)
        {
            this.n = x;
            setChanged();
            System.out.println("ObservableValue says: setChanged() has been called");
    
    //      notifyObservers(new Integer(this.n));
            notifyObservers();                                                                  // makes the observers print null
            System.out.println("ObservableValue says: notifyObservers() has been called");
        }
    
        public void start()
        {
            new Thread(this).start();
        }
    
        public void run()
        {
            int count = -1;
            int a=0, b=0;
    
            while(a==b)
            {
                if(count != n)
                {
                    count = n;
                    System.out.println("ObservableValue says: My count is: [" + count + "]");
    
                    count++;
                    System.out.println("ObservableValue says: Now my count is: [" + count + "]");
                    setChanged();
                    System.out.println("ObservableValue says: setChanged() has been called");
    
                    notifyObservers(new Integer(count));
                    System.out.println("ObservableValue says: notifyObservers() has been called");
    
                    System.out.println("ObservableValue says: Sleeping for 5 second(s)");
    
                    try
                    {
                        Thread.sleep(5000);
                    }
    
                    catch (InterruptedException e) { e.printStackTrace(); }
                }
            }
        }
    }
    

我非常感谢有关这些概念的最佳实践的任何指示/建议/意见。

请帮助。

java multithreading oop inheritance observer-pattern
2个回答
3
投票
  1. 您不需要将Observable实例引用传递给观察者;这实际上是一个坏主意,因为您可以在Observable方法中引用update()实例和修改后的值。另外,如果您不将观察者绑定到特定的Observable实例,则可以将其附加到其他Observable上,而无需进行任何修改。

  2. 对于使用多个观察者,您不一定需要多个类。就您而言,您可以使用同一类的多个实例来实现所需的功能。


2
投票
  1. 尝试将更新方法更改为此:

    public void update(Observable o, Object arg)
    {
        if (o instanceof ObservableValue){
            ObservableValue obs = (ObservableValue) o;
            System.out.println("MyObserver1 says: Value changed to: [" + obs.getValue() + "]");
        }else{
            System.out.println("The observable object was not of the correct type");
        }
    
    }
    

这将允许您访问需要的可观察对象上的任何方法,以便获得所有可能已更改的值并进行相应更新。

2我在您的类之间看不出太大的区别,您不仅可以为这些观察者创建一个新实例,还可以为每个观察者都拥有一个完整的类吗?

我已经删除了我认为不需要的类,并显示了如何使用一个观察者类来完成此操作(除非每个类都需要不同的功能)。它们的编号与以前一样。

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

public class ObserverPatternMultipleObserversUsingThreads
{
    public static void main(String[] args)
{
    ObservableValue observableObj = new ObservableValue(10);

    MyObserver observer1 = new MyObserver(observableObj);
    MyObserver observer2 = new MyObserver(observableObj);

    observableObj.addObserver(observer1);
    observableObj.addObserver(observer2);

    observableObj.start();

    System.out.println("Calling Listeners");

    observer1.printObservablesValue();
    observer2.printObservablesValue();

    System.out.println("Main thread says: Sleeping for 3 second(s)");

    try
    {
        Thread.sleep(3000);
    }

    catch (InterruptedException e)
    {
        e.printStackTrace();
    }

    System.out.println("Main thread says: Going to change Observables Value");

    observableObj.setValue(20);
    }
}


class MyObserver implements Observer
{
static int numberOfObservers = 0;
private ObservableValue obsValObj = null;
private int observerNumber;

public MyObserver(ObservableValue obsVal)
{
    numberOfObservers++;
    observerNumber = numberOfObservers;
    this.obsValObj = obsVal;
}

public void printObservablesValue()
{
    System.out.println("MyObserver"+observerNumber+" says: [" + obsValObj.getValue() + "]"); 
}

public void update(Observable o, Object arg)
{


    if (o instanceof ObservableValue){
        ObservableValue obs = (ObservableValue) o;
        System.out.println("MyObserver"+observerNumber+" says: Value changed to: [" + obs.getValue() + "]");
    }else{
        System.out.println("The observable object was not of the correct type");
    }

}
}

class ObservableValue extends Observable implements Runnable
{
    private int n = 0;

    public ObservableValue(int x)
{
    this.n = x;
}

public int getValue()
{
    return n;
}

public void setValue(int x)
{
    this.n = x;
    setChanged();
    System.out.println("ObservableValue says: setChanged() has been called");

//      notifyObservers(new Integer(this.n));
    notifyObservers();                                                                      // makes the observers print null
    System.out.println("ObservableValue says: notifyObservers() has been called");
}

public void start()
{
    new Thread(this).start();
}

public void run()
{
    int count = -1;
    int a=0, b=0;

    while(a==b)
    {
        if(count != n)
        {
            count = n;
            System.out.println("ObservableValue says: My count is: [" + count + "]");

            count++;
            System.out.println("ObservableValue says: Now my count is: [" + count + "]");
            setChanged();
            System.out.println("ObservableValue says: setChanged() has been called");

            notifyObservers(new Integer(count));
            System.out.println("ObservableValue says: notifyObservers() has been called");

            System.out.println("ObservableValue says: Sleeping for 5 second(s)");

            try
            {
                Thread.sleep(5000);
            }

            catch (InterruptedException e) { e.printStackTrace(); }
        }
    }
}
}

0
投票

我认为您应该始终使用OOP概念很好地定义谁可以做什么。

对于您拥有的示例,我将在Observable对象内创建一个列表,其中包括:AddObserver,RemoveObserver和NotifyObservers(每次需要通知某些内容。

[Here,我们有一个新闻社,带有观察员列表(报纸),每当新闻到来时,都会自动通知已注册的观察员。

© www.soinside.com 2019 - 2024. All rights reserved.