Observer/Observable vs. EventListener

Can anybody tell me why Observer/Observable would be used in a situation rather than implementing EventListener? On the surface they seem redundant, but I'm hoping there's an explanation as to when and why you would use one over the other.
Thanks.
craig

I've been wondering the same thing myself and have been able to make the following reasonings:
- The Java Observer-Observable mechanism is "quasi-transactional" in the sense that Observers are not strictly notified when any change is made, but rather when the Observer decides to notify its registered Observers. Observers can still inquire (via hasChanged) if the Observable has been updated, so atomicity is not guaranteed for a set of changes (short of providing a bulk mutator).
- The EventListener pattern is littered with various support implementations for firing events. The java.beans package has support classes for its listeners, as do AWT and Swing. In general the EventListener pattern is more of a pure pattern since the implementation is not embedded (as with the Observer-Observable mechanism).
- The Observer-Observable mechanism seems to predate the JavaBeans specification in the naming conventions. I am personally not a frequent user of IDE's, so the following statement may be way off, but is an educated guess: It's quite likely that most IDE's cannot introspect the Observer-Observable mechanism the way they can with the EventListener pattern.
- Referrent to the previous item, it is also not possible to use the standard JavaBeans Introspector to get an EventSetDescriptor for a JavaBean that implements an Observer. (A brief examination of the sources for Introspector shows this to be the case. I suppose one could write a custom BeanInfo to make an aggregated or superclass Observer appear with an EventSetDescriptor...)
- The notification parameter for the Observer-Observable mechanism is an Object.
- The notification parameter for an EventListener is an EventObject with some concrete extension that is commensuate with the events processed by the EventListeners.
As I type this, I think I've convinced myself that the EventListener mechanism is probably preferrable in general to the Observer-Observable pattern for the following reasons:
- First-class introspection support.
- Limited contortions to make use of the framework (refer to the countless threads asking for advice on how to use the Observer-Observable mechanism without resorting to aggregation and subclassing).
The main contention that I'd had with EventListeners over the Observer-Observable mechanism has been the quasi-transactional nature of the latter. In particular, it's nice to sometimes bundle changes to an object before sending out change notifications, especially with GUI applications (versus an "update-model-then-update-views-some-time-later" approach.) Nevertheless, it's possible to bundle change notifications with EventListeners. I guess I was wrapped up in using a PropertyChangeListener which has a property-by-property-change-notification nature.
Hope my musings help...

Similar Messages

  • Help please on Observer / Observable and Serial Communications!

    Help!
    I have a project where I need a java application to talk to some test equipment via the serial port. I have studied the java comm api and played around with the SerialDemo example which I used to model my code.
    I have a SeialConnection class which is very similar to the example except I made it to extend Observable and I have it notify observers when data is detected on the serial port.
    I created a second class which extends Obserable which communicates with the SerialConnection and implemented the observer interface. This class process the incomming and outgoing data and provides some higher level methods, like getSerialNumber(), for my application to use. The application frame is an Observer of this class so the GUI can show the status as well.
    An example method from this class:
    private String Get590AROMString() {
    SendString("EZR-V"); //Send a command to the s.p.
    serialConnection.pause(750); //Basically a sleep(750)
    return ROMVersion; //Return the data from update()
    Excerpt from update method:
    // If return from serialConnection starts with VER: parse the RV and SN.
    if(T.startsWith("VER:")) {
    ROMVersion = new String(T.substring(0,T.indexOf('~')));
    SpeciesName = new String(T.substring(T.indexOf('~')+2));
    return;
    This works great when the test equipment sends a message or when the user selects a command from the program interface. My problem is when I try to send a command to the serial port from within the update method of the observer. There are instances where a result from the serial port needs to initiate another request for information.
    Here is a fragment from the update method of the application frame:
    public void update(Observable obs, Object obj) {
    DensTalkStatus DTS;
    if( obs==DT ) {
    DTS = (DensTalkStatus)obj;
    else if(DTS.GetStatus()==DensTalkStatus.NOTIFY_ZEROOK) {
    if(FIRSTCONNECT590A) {
    GDD.GetDensimeterInfo(); // *** This is the Request
    GDD.SetDensID(EDM);
    FIRSTCONNECT590A = false;
    When I make a request for additional information from the serial port within the update method I get nothing returned and the requested data arrives later after the update method has completed.
    I do not know the fine details of how the javax.comm or observer/obserable works but it appears to me that my strategy can only process one command at a time.
    Can anyone think of a way to allow the application's frame update method to request information and wait for the data to be ready?
    Does anybody have an example of how to do this type of communications?
    I am sorry for the length of this question... Thank you for your time.
    Doug

    I have not received any suggestions yet on an alternate method for this problem, but I have come up with a solution I think will work. I am posting it here so others who have the same problem can at least see what path I followed...
    The basic problem seems to be that I am trying to have my observer ask for information that requires the same observer / observable thread to respond.. duh! :) To requst additional information from the serial port I need to move the requests out of the update() method to a different thread.
    I implemented the SerialWorker class to make the request so the observer update() method could return normally without waiting for the result of the new request.
    Doug

  • RMI + Observable/Observer trouble

    I'm trying to develop the following:
    Local:
    A Swing JFrame object which contains some JPanels that should Observe the actions of server's BusinessLogic.java
    Both sides:
    An interface that contains the declaration of the methods in server's business logic.
    RemoteObserver.java
    RemoteObservable.java
    RemoteObserverImpl.java
    RemoteObservableImpl.java
    Server:
    One Observable class that contains the business logic and notifies some changes and implements the Interface.
    Other classes.
    I'm using the latest JDK version.
    I have some classes to do the RMI + Observable/Observer thing but I don't know how to apply them to my application.
    Here's what i've done so far:
    public class MainFrame extends JFrame {
         public static final String serviceName = "RemoteServer";
         private String host = "localhost";
         private RemoteBusinessLogicInterface remoteLogic;
         public MainFrame(String frameTitle) {
              super();
              setTitle(frameTitle);
              setSize(700, 600);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              System.setProperty("java.security.policy", "client.policy");
              setRemoteServer();
              ObserverPanel observerPanel = new ObserverPanel(
                        remoteLogic);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(observerPanel, BorderLayout.CENTER);
              this.setVisible(true);
         public void setRemoteServer(){
              try {
                   if (System.getSecurityManager() == null)
                        System.setSecurityManager(new RMISecurityManager());
                   String rmiUrl = "rmi://" + host  + "/" + serviceName;
                   remoteLogic = (RemoteBusinessLogicInterface) Naming.lookup(rmiUrl);
              } catch (ConnectException ex) {
              } catch (UnknownHostException ex) {
              } catch (Exception ex) {
         public static void main(String[] args) {
              MainFrame f = new MainFrame("Title");
    public class ObserverPanel extends JPanel{
         private DefaultListModel items;
         private JList list;
         public ObserverPanel(RemoteBusinessLogicInterface remoteLogic) {
              items = new DefaultListModel();
              list = new JList(items);
              list.setVisibleRowCount(24);
              JScrollPane scrollPane;
              scrollPane = new JScrollPane(list);
              setLayout(new BorderLayout());
              add(scrollPane,BorderLayout.CENTER);
         public void update(RemoteObservable observable, Object objektua) {
              System.out.println("Change notified");
    public interface RemoteBusinessLogicInterface extends RemoteObservable{
         public void insertData(int number, String code, Date date) throws RemoteException;
         public void submit() throws RemoteException;
         public void clear() throws RemoteException;
    class RemoteBusinessLogic extends RemoteObservableImpl implements
              RemoteBusinessLogicInterface {
         public static final String serviceName = "RemoteServer";
         public RemoteBusinessLogic() throws RemoteException {
         public void clear() throws RemoteException {
              setChanged();
              super.notifyObservers();
         public void insertData(int number, String code,
                   Date date) throws RemoteException {
              System.out.println("Something");
              setChanged();
              super.notifyObservers();
         public void submit() throws RemoteException {
              System.out.println("Something");
              setChanged();
              super.notifyObservers();
         public static void main(String[] args) {
              System.setProperty("java.security.policy", "client.policy");
              if (System.getSecurityManager() == null)
                   System.setSecurityManager(new RMISecurityManager());
              try {
                   RemoteBusinessLogic serverObject = new RemoteBusinessLogic();
                   try {
                        java.rmi.registry.LocateRegistry.createRegistry(1099);
                        Naming.rebind(serviceName, serverObject;
                        System.out.println("Server launched");
                   } catch (MalformedURLException e) {
                   } catch (Exception e) {
              } catch (RemoteException e1) {
    }RMI works OK, but I don't know how to tell the server which are his observers. I know I have to use the addObserver (RemoteObserver ro) method but I don't know how to tell the server which are the GUI instances (which are the observers) so that I can add them.
    Any help will be welcomed. Thanks.
    Bye.

    Hello Vitor,
    Simply have your clients give your observable server object a remote reference to their observer object.
    It would look something like this:
    server.addObserver(new Remote(myObserver));Your server object would keep a list of its observers, and call them whenever it wants, using some interface method like:observer.stateChanged(someData);Essentially, design it just as if the observers were local.
    John

  • Observer-observable pattern question

    Hi all there!!
    I reckon that in the observer-observable pattern, there is an notfiyObserver(object obj) method to invoke the Observer to receive the reference instance obj, and in the observer class, as there is a method called update(observable obr, object obj2), obj is subsituted into obj2 to complete the whole process. so obj from Observable is sent to Observer as obj2. Am i right?
    Because I've tried such thing, but seems that the observer receives null object...... sorry that I'm not going to post the code here /_\!! Thank you

    Are you sure you are calling notifyObservers(Object arg) and not just notifyObservers()? Because in the later case, the "observer" would receive null as a second argument in its "update" method.
    Try to print or do some operation on your arg object before passing it in notifyObservers method to see if it's really not NULL.
    Hope this helps..

  • Observer/Observable design pattern

    Is there a way to implement the Observer/Observable pattern in a pure java FX 1.2 desktop Application?
    And if yes how ? :)

    You can use the real stuff, as shown in some threads (eg. in [Cannot bind a string array|http://forums.sun.com/thread.jspa?threadID=5425718] I show an example).
    This is necessary only to bind Java variables to JavaFX code.
    Now, as said above, in pure JavaFX code, you use binding. And the 'on replace' facility is useful too, as changes trigger actions.

  • URGENT - Client,UI,Observable & Observer

    I have a Client who receives packets from
    other Clients or the server.
    This Main class for Client creates a "User Interface
    class".And then the UI class creates the
    "Central Class" which deals with packet handling etc.
    When I receive a packet, "Central" unpacks it
    and need to notify the "UI" class and send
    some info(Event Object May be) for
    "UI" to display it.
    I read a post on Observable and Observer class.
    so I can make Central Class extend Observable
    so it can notify the Observer, which will be UI
    BUT!!
    In order to use Observable & Observer,
    It is required to add Observer to Observerable
    by doing addObserver(object o)
    in Observable class.
    But Observable class is created IN the Observer
    class. So how can I pass the object for the
    addObserver method?
    any help is really appreciated,
    thanks in advance.
    << may reply to [email protected] >>

    I have a Client who receives packets from
    other Clients or the server.
    This Main class for Client creates a "User Interface
    class".And then the UI class creates the
    "Central Class" which deals with packet handling etc.
    When I receive a packet, "Central" unpacks it
    and need to notify the "UI" class and send
    some info(Event Object May be) for
    "UI" to display it.
    I read a post on Observable and Observer class.
    so I can make Central Class extend Observable
    so it can notify the Observer, which will be UI
    BUT!!
    In order to use Observable & Observer,
    It is required to add Observer to Observerable
    by doing addObserver(object o)
    in Observable class.
    But Observable class is created IN the Observer
    class. So how can I pass the object for the
    addObserver method?
    any help is really appreciated,
    thanks in advance.
    << may reply to [email protected] >>
    After creating the Observable try addObserver(this)

  • Notify/Wait or Observable/Observer?

    Hi,
    I have one thread process the data and store the result in a data object. Several threads access the data object to display.
    Which one to use:
    1) Have the processing thread notify the display threads when it's done? Using thread wait()/notify()?
    2) Have the data object be the observable, and the dislay threads be the observers? Using the observable/observer concept?
    Thanks

    How exactly would you code the wait/notify method calls? I had dynamic data that was used to update the data models for a JList and a JTable, and found it difficult to notify the models correctly, after the data changed.
    Somehow the object has to "post" the fact that it has changed, a job for Observer/Observable. The Thread tutorial and the various Swing tutorials don't quite describe this in a way I understand. Can somebody give an example of how to use notify/wait in this sort of situation? Thanks.

  • Are Observer/Observable still alive?

    Hello. I can't understand why one should use these classes instead of the very common event listening model, composing with, or subclassing, EventListenerList.
    I also didn't find any recent code which uses Observer/Observable?
    Enrico

    Hello. I can't understand why one should use these
    classes instead of the very common event listening
    model, composing with, or subclassing,
    EventListenerList.
    I also didn't find any recent code which uses
    Observer/Observable?
    EnricoI prefer the names of the Observer / Observable classes but I think they aren't used because Observable is a class. Since there is no multiple inheritance in Java, it's not very useful. I have found the java.beans.PropertyChangeEvent, PropertyChangeListener, and PropertyChangeSupport classes to be a good replacement.

  • Observable/observer nightmare

    I'm currently simulating a robot with a graphical front end linked to a model using a model-view architecture. In fact there are two views running in parallel: a graphical representation and a set of JLabels displaying parameters of the model as they change. I have recently discovered that making the model extend the Observable class and the views implement the Observer interface is the way forward.
    However, this has messed up my architecture. Before, the model was a member of both the view classes. i.e. the model does not see the views. Unfortunately, the model needs to see the views to register them as Observers. What can be done? Is there a simple example of how to use the observing techniques properly?

    You also wanted an example, so, here goes.....
    Assuming that you dont change your listeners very much (and by the sounds of it, you dont), you can do something like the following (If you do change them around quite a bit, consider using AWTEventMulticaster).
    // The model that you can watch:
    public interface RobotModel
      public void addRobotListener(RobotListener r);
      public void removeRobotListener(RobotListener r);
    // The listener
    public interface RobotListener
      /* Note: You may want to consider giving an actual
         'change event' to describe the change - but In the
         simple case, your view can query the model when
         it knows it's been updated
      public void robotModelChanged(RobotModel aModel);
    // Impl
    public class YourModel implements RobotModel
      private List mListenerList;
      public YourModel()
       mListenerList=new LinkedList;
      public void addRobotListener(RobotListener aListener)
        /* Need to sync on the list - if you add/remove quite
           a lot, consider AWTEventMulticaster instead
        synchronized(mListenerList)
          if(!mListenerList.contains(aListener))
            mListenerList.add(aListener);
      public void removeRobotListener(RobotListener aListener);
        /* Again, sync on the list  */
       synchronized(mListenerList)
          mListenerList.remove(aListener);
      protected void pNotify()
        /* Call this when you want to notify your listeners
           of a change to your model
        synchronized(mListenerList)
          Iterator anIterator=mListenerList.iterator();
          while(anIterator.hasNext())
            RobotListener aListener=(RobotListener)anIterator.next();
            // Do the notification:
            aListener.robotModelChanged(this);
      /* Example of changing something */
      public void changeSomethingInTheModel()
        // Do the change, then:
        pNotify();
    // Your view:
    public class ViewImpl implements RobotListener
      private RobotModel mModel;
      public ViewImpl(RobotModel aModel)
        // You said the view knew about the model:
        mModel=aModel;
        // register as a listener to the model:
        mModel.addRobotListener(this);
      // We receive notification of changes thru this method:
      public void robotModelChanged(RobotModel aModel)
        if(aModel!=mModel)
          // receiving dodgy notification!
          // (probably dont need this check in practice!)
        else
          // Model updated - query the model and update
          // the view!
    }Note that your model does NOT need to know about a view - it just needs to know about a RobotListener.
    Dave.

  • Observable Observer Model

    Hi,
    I am implementing Event Service for that
    I have two classes
    1]
    One class extends Observable and another implements Observer.
    whenever i get event i put it in memory Queue which is nothing but Vector and notify observer about this change
    now my observer gets that event and checks for matching subscribers and send event to those matching subscribers
    the problem i am facing is
    whenever observable class notify observer class
    unless and until update method is finished processing in observer class , observable class has to wait
    Please help in solving problem
    Thanks in advance

    This is my observable class
    package .....
    import java.util.*;
    public class InMemoryEvents extends Observable
         private static Ve
    ctor inMemRepository = new Vector();
         public InMemoryEvents()
              addObserver(new EventsHandlerThread());
    public Document Add2Stack(Document _doc) {
              try
                   inMemRepository.addElement( _doc );
                   sendMessage(_doc);
              catch(Exception e)
                   e.printStackTrace();
                   return           }
              return dom ;
    public synchronized void sendMessage(Document _doc)
              System.out.println("IN SEND MESSAGE");
              setChanged();
              notifyObservers(_doc);
    ===============================================================
    class EventsHandlerThread implements Observer
    public EventsHandlerThread()
    public void update(Observable o,Object arg)
              message=(Document)arg;
              notify();
    bun();
              System.out.println("--------------- hello --------");
              Vector v = InMemoryEvents.getVectorInstance();
              System.out.println(v);
              message = null;
    public void bun()
                   System.out.println("----------WAITING FOR THE EVENT TO COME----------");
                        while(message==null)
                             try{
                                  wait();
    in other methods i get events from vector and find matching subscribers for it
    Explantation :
    I have a memory queue where i am putting my events in as and when they come (i.,e in Vector)
    This is my observable class
    One observer is observing on that memory
    as soon vector gets one or more events observer will be nofitied by the observable about this change
    and update method gets called
    Now when update method is going on observable is waiting on that method ( That is what i found )
    I want to avoid this situation cos events are coming in continously
    Please help me its urgent
    Post some code if u have
    Thanks i advance

  • Observer - Observable

    I'd like to port a simple app to a MIDlet.
    However, it makes use of the java.util Observer interface and Observable class (to notify GUI that it needs to update when data has changed).
    How can I best implement this functionality in a MIDlet?

    You will have to implement the code for the classes java.util.Observer and java.util.Observable. It would be quite simple to implement the classes. You can have a look at the JDK source code.
    The only data structure you would need is a Vector of Observer
    objects inside the Observable class that you write. It would be
    rather simple to implement...really.

  • Observer& Observable in Java

    Can any one pls give one small example of how observers and observalbe is used in java.

    Hi,
    This sounds like homework. What does your textbook say? Have you tried to google, or search the forum?
    Kaj

  • Observable vs Custom Events

    Hi.
    I'm creating a project that uses the MVC design pattern, and being eager to make sure I follow the best practices I have a couple of questions. When notifying a 'View' of changes to the 'Model' is it preferable to effect this notfication using the Observer/Observable pattern, or through a custom eventListener? I can understand that the Observer/Observable way of doing things allows the View to be completely independant of the Model. However if I were to use custom events and eventListeners it would certainly make things easier to read and implement (my model is quite a large beast, comprising of multiple sub-models), as I would be able to provide more information about the change with each notification.
    Is the answer to this just personal preference, or is there a convention?
    Thanks in advance.

    EventListener is an example of the [Subject] Observer
    pattern.
    If you are using swing/awt then use EventListener, if
    you wish to decouple your implementation from
    swing/awt, then implement your own solution based on
    the [Subject] Observer pattern.I disagree. Swing/awt have nothing to do with this. EventListener, EventObject, Observer, and Observable all belong to java.util. In theory you could do this without using any of these classes and making the event and listeners yourself without extending anything from java.util.
    Observer and Observable is good for a one to one relationship. It is quick, easy to do, and you don't have a lot to worry about. Multiple Observers watching one Observable is also nice. It is when you start watching multiple Observable classes that things get messy. Observer has one method that all Observable classes call. You have to do a lot of checking to see which class the Observable is before you know how to handle it.
    IMO the biggest disadvantage to Observer and Observable, is that something must extend Observable. This is bad if the class you want to observe extends something else. Instances of Observer and Observable are also bound tightly together.
    Events and Listeners are not bound together. Typically once the event is processed, it is disposed unless you want to save it and use it over and over. When using multiple listeners and events, you would implement each listener (or make anonymous) and it would have its own methods for a specific event, and not one large update method that handles everything. The events would be constructed as needed, and passed to the listeners.
    You are not limited to extend Event like you are with Observable. If you tried to handle an Observable the same way as an Event, you would have to register the Observable with the Observer, notify the Observer, then remove the Observable.
    Event/Listener is awesome for multithreading. You could write a Thread and Queue to manage all of your events (Similar to the AWTEventQueue). A class could put an event into the queue to be processed at a later time (or right away) by another thread. The Observer/Observable relationship cannot support this easily.
    The disadvantage is that you have to handle sending an event to each listener manually, where the Observer/Observable handles that on its own.
    In summary, Observer/Observable is a slightly more limitted version of Event/Listener, but it handles notifying the Observer/Listener on its own.

  • How to implement Observer Pattern?

    Hello guys,
    I have some problems with implementing the observer pattern. So i m making an sound application and i need to put a meter changing with the volume.
    I have already the meter designed and the volume is calculated.
    So i have a class called Application (is the main class) and this class have the graphic designer from the application, makes the audio capture and calculate the volume.
    And i have the MeterMic class and in this class i have the graphic Meter where i send this graphic meter to the application via JPanel.
    In MeterMic i have the variable "value" and this variable will make the changes in the bars of the meter and i want to equal the value to the volume from the application. I try referencing by the Application object but doesnt pass the value from the volume.
    So i would like to implement the Observer pattern.
    I need to observ the variable volume and than the volume have changes i want to send that change to variable value in MeterMic.
    My problem is: who is the observer and observ? And what i need to do to implement the pattern.
    My best,
    David

    Kayaman wrote:
    DavidHenriques wrote:
    So i just need to implement the observers interfaces and than implement the method update and notify in the classes.You should probably forget the Observer/Observable classes, they're Java 1.0 stuffDo you think they are usless just because they are old?
    so you don't have to or need to use them, even though the names sound appealing.I still like them because the Observable saves me from repetitively implementing (hopefully thread save) method for notifying the observers...
    It's basically the same thing, you just see a lot more talk about Events/Listeners than Observers/Observables these days.The good thing on Events/Listeners is that they are type save which is an importand feature.
    But I like to build them on top of Observer/Observable on the event source side.
    bye
    TPD

  • Observer Pattern applied in Abap

    Observer Pattern
    Observer pattern is a well known pattern especially with Java, here i continue my work in patterns.
    This is my humble understanding of a way how we can apply observer pattern
    The main components of this pattern is:
    Observer pattern:
    Subject
    Observer
    Context
    Why do we need?
    Cant i do without this pattern, well of course you can do although you will be having a tightly coupled application
    The main reason is we don't want to couple the objects
    The main goal is the " Least knowledge in objects across each other"
    The trick here is the use of the Events in ABAP where an event gets raised and then that will be handled by a listener!!
    Subject:
    Its the main object the core data that we will be working with
    You could have multiple implementations of the subject
    One approach: is to have an interface where we can extract the event.
    Here is a code sample: Subject is data based on the sales order item data when there is a change it will fire the event below
    interface lif_subject.
       EVENTS: SUBJECT_IS_CHANGED.
    ENDINTERFACE.
    Here is the subject:
    class lcl_subject definition .
    public section.
    INTERFACES lif_subject.
       methods CONSTRUCTOR
         importing
           !IV_MATNR type MATNR
           !IV_SPRAS type SPRAS
        methods GET_MATNR
         returning
           value(RV_MATNR) type MATNR .
       methods GET_SPRAS
         returning
           value(RV_SPRAS) type SPRAS .
        methods SET_MATNR
         importing
           !IV_MATNR type MATNR .
       methods SET_SPRAS
         importing
           !IV_SPRAS type SPRAS .
    protected section.
    private section.
       data MV_MATNR type MATNR .
       data MV_SPRAS type SPRAS .
    ENDCLASS.
    CLASS lcl_subject IMPLEMENTATION.
    METHOD constructor.
       mv_matnr = iv_matnr.
       mv_spras = iv_spras.
    ENDMETHOD.
    METHOD get_matnr.
       rv_matnr = mv_matnr.
    ENDMETHOD.
    METHOD get_spras.
       rv_spras = mv_spras.
    ENDMETHOD.
    METHOD set_matnr.
       mv_matnr = iv_matnr.
       RAISE EVENT lif_subject~SUBJECT_IS_CHANGED.
    ENDMETHOD.
    METHOD set_spras.
       mv_spras = iv_spras.
       RAISE EVENT lif_subject~SUBJECT_IS_CHANGED.
    ENDMETHOD.
    ENDCLASS.
    Observer:
    Observer is the one thats interested in the change of the subject
    That could be any observer
    Here is the code sample
    ****Observer
    INTERFACE lif_observer.
    METHODS: update.
    ENDINTERFACE.
    class lcl_observer1 DEFINITION.
    PUBLIC SECTION.
    INTERFACES lif_observer.
    ENDCLASS.
    class lcl_observer1 IMPLEMENTATION.
    method lif_observer~update.
    WRITE:/ ' Observer 1 is updated '.
    ENDMETHOD.
    ENDCLASS.
    class lcl_observer2 DEFINITION.
    PUBLIC SECTION.
    INTERFACES lif_observer.
    ENDCLASS.
    class lcl_observer2 IMPLEMENTATION.
    method lif_observer~update.
    WRITE:/ ' Observer 2 is updated '.
    ENDMETHOD.
    ENDCLASS.
    Context:  Its the manager of the all communication like a channel
    It separates the observer from the observable.
    class   lcl_channel  definition.
    PUBLIC SECTION.
    methods: add_observer IMPORTING io_observer type REF TO lif_observer.
    methods: remove_observer IMPORTING io_observer type REF TO lif_observer.
    methods: constructor.
    methods: notify_observers FOR EVENT lif_subject~SUBJECT_IS_CHANGED of lcl_subject IMPORTING sender.
    PRIVATE SECTION.
    DATA: lo_list type REF TO CL_OBJECT_MAP.
    class-DATA: lv_key type i.
    ENDCLASS.
    Notice that the event listener for the subject is the channel itself
    and notify_observers method is responsible for that.
    ****Manager!!
    class   lcl_channel  definition.
    PUBLIC SECTION.
    methods: add_observer IMPORTING io_observer type REF TO lif_observer.
    methods: remove_observer IMPORTING io_observer type REF TO lif_observer.
    methods: constructor.
    methods: notify_observers FOR EVENT lif_subject~SUBJECT_IS_CHANGED of lcl_subject IMPORTING sender.
    PRIVATE SECTION.
    DATA: lo_list type REF TO CL_OBJECT_MAP.
    class-DATA: lv_key type i.
    ENDCLASS.
    class lcl_channel IMPLEMENTATION.
    method constructor.
       create OBJECT lo_list.
       lv_key  = 1.
    ENDMETHOD.
    method add_observer.
    lo_list->PUT(
       EXPORTING
         KEY      = lv_key
         VALUE    = io_observer
    lv_key = lv_key + 1.
    ENDMETHOD.
    method remove_observer.
    ENDMETHOD.
    METHOD notify_observers.
    DATA: lo_map_iterator TYPE REF TO CL_OBJECT_COLLECTION_ITERATOR.
    DATA: lo_observer type REF TO lif_observer.
    break developer.
    lo_map_iterator ?= lo_list->GET_VALUES_ITERATOR( ).
    while lo_map_iterator->HAS_NEXT( ) = abap_true.
    lo_observer ?= lo_map_iterator->GET_NEXT( ).
    lo_observer->UPDATE( ).
    ENDWHILE.
    ENDMETHOD.
    Notice the use of the Collections as well cl_object_collections object in SAP Standard
    I hope you find this useful
    The sample code is attached as a text file
    ENDCLASS.

    Are you asking to check string in data in the course of running the program, or are you asking how to check patterns in the source of the program itself?
    The other replies have covered checking patterns in data.
    If you want to check for patterns in the ABAP source itself, you can check for patterns in ABAP source using SCII Code inspector.
    Enter SCII and select the object or set of objects to check.
    Under the list of checks for Temporary Definition there is area called
    Search Functs.
    Under Search Functs., if you expand it, there are options to search for
    Search of ABAP Tokens
    Search ABAP Statement Patterns
    Click on the arrow to the left of these and you can specify details about the patterns that you want to search for.
    Good luck
    Brian

Maybe you are looking for