How can I use observer design pattern?

拟墨画扇 提交于 2020-01-24 13:10:39

问题


I need to use the Observer design pattern for a school project, but I'm having problems with it. I have a timer and an int which decrements itself, I want to make an observer so when the int becomes 0, a jdialog pops up.

Here is my code:

 public class Joc extends JPanel implements ActionListener {
 javax.swing.Timer t1;
 int time=0,
 MyObservator obs = new MyObservator();

   public Joc()
   { ... // constructor stuff
    t1=new javax.swing.Timer(1000, (ActionListener) this);
    t1.start();}

   public void actionPerformed(ActionEvent e) {
   if(time>0) {time--;}
   else {}
   }

// My observator class

public class MyObservator implements Observer{
Joc joc;
MyJDialog dialog;

 @Override
public void update(Observable o, Object arg) {
    if(joc.time==0)
    {dialog.setVisible(true);}
}

}

I didn't understand how to use the observer, how can I make add the observer and how can I make it function?


回答1:


With the observer pattern you start with a basic interface for an observer. The observers notify method will be called by some other class when a particular event occurs.

public interface IObserver {

    public void notify(int i);
}

Now the interface needs an implementation:

public class Observer implements IObserver {

    @Override
    public void notify(int i) {
        if(i % 1000 == 0){
            System.out.println("One thousand iterations elapsed.");
        }
    }

}

The observable needs something to observe. So a class is created that contains a list of IObservers. Notice that IObservers can be added to the list contained by the Observable. If desired, the addObserver method can be specified in an interface which is then implemented by Observable. Also notice that the Observable class calls the notify method when a particular event occurs. The IObserver is notified of these events and can perform any action when they occur. In our example, if the int is 1000 we print some text to the console.

public class Observable {

    private List<IObserver> observers = new ArrayList<IObserver>();

    public void addObserver(IObserver observer){
        this.observers.add(observer);
    }

    public void execute(){
        for(int i = 0; i < 10000; i++){
            for(IObserver observer: observers){
                observer.notify(i);
            }
        }
    }
}

In a program we register instances implementing IObserver with the Observable instance.

public static void main(String[] args) {
    Observable observable = new Observable();
    observable.addObserver(new Observer());
    observable.execute();
} 

In your example, the Joc class is equivalent to the Obserable class. It should contain a list of Observers and notify them when a particular event occurs via the update method.



来源:https://stackoverflow.com/questions/16742055/how-can-i-use-observer-design-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!