问题
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 IObserver
s 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 Observer
s and notify them when a particular event occurs via the update
method.
来源:https://stackoverflow.com/questions/16742055/how-can-i-use-observer-design-pattern