dcsimg
will you give me some examples about Observer and Observable's use?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   bean_java
Posted On:   Wednesday, August 7, 2002 07:32 PM

HI,ALL.

I'm new to java.

would you give me some examples about Observer and
Observable's use?

thanks in advance!

Re: will you give me some examples about Observer and Observable's use?

Posted By:   R_C  
Posted On:   Wednesday, August 7, 2002 07:45 PM

eg recycled from a previous reply, general observer/observable (note interfaces), not swing related.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import java.applet.*;
import java.util.*;



interface MyObservable
{
public void addObserver( Object obj );
public void tellObservers();
//public void removeObserver( Object obj );
}

interface MyObserver
{
public void notify( Object obj );
}

class A implements MyObserver
{
public void notify( Object obj )
{
System.out.println( "A: " + this + " o: " + obj );
}
}

class B implements MyObservable
{
Vector collectionOfVariablesForA = new Vector();

Vector observers = new Vector();

public B()
{
collectionOfVariablesForA.addElement( "first" );
collectionOfVariablesForA.addElement( new Date() );
collectionOfVariablesForA.addElement( new Double( 123.45 ) );
}

public void addObserver( Object obj )
{
observers.addElement( obj );
}
public void tellObservers()
{
for( int i = 0, ii = observers.size(); i < ii; i++ )
{
MyObserver ob = (MyObserver) observers.elementAt( i );
ob.notify( collectionOfVariablesForA );
}
}
public void doSomethingAndTellEveryone()
{
System.out.println( "B doing something tell everyone: " + this );
tellObservers();
}
}

public class Obs
{
private void initialize()
{
B b = new B();
A a = new A();
A aa = new A();
b.addObserver( a );
b.addObserver( aa );
b.doSomethingAndTellEveryone();
}
public static void main( String[] args )
{
Obs obs = new Obs();
obs.initialize();
}
}


About | Sitemap | Contact