The Observer Pattern

I need to help on the Observer pattern. It's true/false questions:
1. The observer pattern lets you vary subjects and observers independently.
2. You cannot reuse subjects without reusing their observers, and vice versa.
3. You cannot add observers without modifying the subject or other observers.
4. The coupling between subjects and observers is abstract and minimal.
5. Like an ordinary request, the notification that a subject sends must specify its receiver.
6. In some situations an observer depends on more than one subject, for example, a spreadsheet may depend on more than one data source.
Thanks
Brendan

Please check if correct. THe reason why I asked for help is because I have not found any good articles on this pattern and it is not part of my curriculum, but we have to answer it.
1. TRUE
2. FALSE
3. FALSE
4. TRUE
5. FALSE
6. TRUE
Please let me knw if I am in the correct direction.
Thanks

Similar Messages

  • Trying to implement the Observer pattern with a notify() method

    OK, I'm not implementing the observer exactly rigidly but I'm doing something thereabouts inline with the pattern. I have an abstract class which provides some common functionality for the observers and is also used for type checking elsewhere. Each observer must inherit from this class. Now; the abstract class has one abstract method notify() as per the generic observer.
    I get an error that notify() cannot be overridden as it's final. I understand what all that means but I'm curious where it's implemented that's actually affecting my own code? Is notify() a standard method in all objects in Java?
    package zoopackage;
    public abstract class ZooObserver
         protected Cage cage;
         public void setCage(Cage myCage)
              this.cage = myCage;
         abstract public void notify();
    }And...
    package zoopackage.observers;
    import zoopackage.*;
    public class VisualObserver extends ZooObserver
         public void notify()
    }

    Is notify() a standard method in all objects in Java?Yes, as are notifyAll() and wait(). You'll also notice in the API that there already is an Observer interface and an Observable object. That's probably sufficient to implement what you want to do.
    Brian

  • How fast is the observer pattern?

    hi,
    let�s say i have a graph with thousands of edges existing.
    Now i delete some of them, but i do not remember, which ones are deleted.
    Deleting should mean in this case i mark them as deleted, by setting a specific flag of the edge object to true.
    If i, lets say "push a button" then i want all edges to switch back to the state of being not deleted.
    If i realize it using Observer and Observable, and i call update(), how fast is this? I think it must be O(n) - with n being the number of Observers, since all observers must be run through, like a link list. But i can be wrong, and it might be much faster?
    Does anybody know about that?
    Thanks a lot for your explanation in advance!
    Message was edited by:
    Cinimood

    let�s say i have a graph with thousands of edges
    existing.
    Now i delete some of them, but i do not remember,
    which ones are deleted.
    Deleting should mean in this case i mark them as
    deleted, by setting a specific flag of the edge
    object to true.
    If i, lets say "push a button" then i want all edges
    to switch back to the state of being not deleted. Walking through the full graph will obviously take O(n), since you need to visit every edge.
    The quickest option is obviously to do remember which ones are deleted: If you delete 10 edges from a 10,000 edges graph, and store these deleted edges in a separate list, you only need to visit those 10 to undelete them.
    But I agree with the previous poster who said that this might not be necessary, for a few thousand nodes the overhead of visiting them all may be hardly noticable.
    Do the simple version first, and do the optimization only if required. It's quite likely that other parts of your application will be more in need of optimization than this one.

  • Observer Pattern

    Hi. I'm coding the observer pattern with generics. All is well up to a point.
    I have an ObserverI interface
    public interface ObserverI
    <     S extends Subject<S,D>,
         D >
         void update( S subject, D details ) ;
    }and a Subject base class
    public class Subject
    <     S extends Subject<S,D>,
         D >
         private List<ObserverI<S,D> > observers = new ArrayList<ObserverI<S,D> >() ;
         public void attach(ObserverI<S,D> observer) { ... }
         public void detach(ObserverI<S,D> observer) { ... }
         public void notifyObservers(D details) {
              for( ObserverI<S,D> observer : observers )
                   observer.update( this, details) ;
    }The problem is the call observer.update( this, details) ; The first argument (this) should be of type S, but is of type Subject<S,D>. Thus I get an error.
    If I replace that line with observer.update( (S) this, details) ;I only get a warning. (Unchecked cast.)
    It seems there should be some way I can express the pattern without the need for any casting or errors. I tried a few things with wild cards
    What can I do? Any help appreciated.

    ejp is right in that the "extends Subject<S,D>" is not needed. Thanks, ejp, for pointing this out.
    But when I get rid of "extends Subject<S,D>" (in both places) I still have the "unchecked cast" warning.
    Since posting the original question, I've learnt a few more things:
    (0) That the cast may be unchecked, but the call is not. Thus even if "this" is not of type "S", there is ClassCastException
    as the argument to update is not of the type expected in the concrete observer. This is reassuring. Crazy stuff does not
    happen!
    (1) That I could solve the whole problem with the "getThis()" trick, as explained by Angelika Langer at http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ205 . (Very helpful FAQ altogether.) That is, replace "this" with a call to an abstract method getThis that returns S. In the concrete subject, getThis is implemented in the obvious way: "return this".
    However, using the getThis() trick seems unsatisfactory, as it forces coders of concrete subclasses of Subject to implement a method for no other purpose than to placate the Generic gods. (In truth there is another justification for using a getThis method, which I may go into in an other post.)
    I'm still hoping someone here can post a better solution.
    Cheers,
    Theo
    Edited by: theodore.norvell on Jun 16, 2009 8:13 PM

  • Observer pattern with TCP

    Hello java friends!
    I have implemented an auction application over a TCP communication. The client's using a basis Socket and the server is multi threaded with a ServerSocket returning a Socket which is processed in a separate thread. The connection between server and client is closed automatic after each request, so another request from the client would need to be connected over a new connection. It's implemented like this for the sake of performance.
    But however, I now want to implement the Observer pattern(which I'm also comfortable with). This would let the client be notified by the server if someone else overbids him in a auction. And I wonder how this could be completed?
    I had a thought and it went like this. If the client would also have a ServerSocket then the server would be able to connect to it when ever he would like to notifying the client. What I like by this implementation is that the notification is done without any delay! This is obviously one way to implement it, but I wonder if someone else in here had a better idea,or if someone knew the standard implementation for a situation like this.
    Thanks in regards!

    superdeportivo wrote:
    The sever creates a new thread for every request that the client makes. If performance is important you may want to use a thread pool.
    For example the client makes a bid on an auction item. [deleted]This is simplest way to do what you require. I am generally in favour of keeping things simple.
    if the Client would like to make another bid then the client would need to go through all the steps again from 1 to 4. Why the fourth step is implemented is because otherwise the client would held a thread live at the server as long as he is connected (using the application) and eventually the server would run out of threads!How many clients do you have at once? You should be able to support 1,000 on a typical PC and 10,000 on a decent server. You can keep the connection/thread for a period of time and drop the connection if the client disconnects or doesn't do anything for a period of time (from a few seconds to a few hours)
    Another approach is to use non-blocking IO (see the samples which come with the JDK) In this way a small number of threads can manage a large number of connections.
    So lets say if we're using a thread pool with maximum 20 threads, then only 20 clients would be able to connect to the server at the same time (use the application). If the maximum is 2,000 then you can have up to 2,000 clients.
    I hope I made my self clear if not please tell me which part wasn't.I think you have made a few assumptions about what performs best or what is possible could have a rethink.
    And about the delay, of course the connection delay is what's acceptable for my program.The simplest approach using your current model is for the client to poll the server.
    Edited by: Peter__Lawrey on 30-Jan-2009 22:56

  • 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 in J2EE

    I have a question about the Observer patterne.
    I have tried to implement it im my application but without result. First my idea was to save all the client Object references in A linked List in a bean on the server. Then each time a certain event ocurs on my server I will call a method fire() which iterate through my linked list and finds all my client references. Then I will make a "call back" to all the clients which are in my linked list. But my teacher tells my that is not the way to do. He belives that there is a much easier way to make sure that all the clients get updates. But he does't know how to do it. So my question is how do I implements Observer Design patterns in the J2ee enviroment ??

    It seems to that one of the solotions to this problem is to use RMI. Apperently it is not possible to make a regular callback to a client in the J2EE enviroment. That,s not good, because you have to make a call back if you want to implement the observer deign patterne. I think it is sad, because one of the most important design pattern is The observer pattern.

  • ActionListener demonstrate Observer Pattern?

    Would using ActionListener in a program be considered an example of the observer pattern?

    I think you should make sure that the object which uses or displays the data is seperate from the object which contains it.
    If this is homework you may get extra marks if you display data changes in more than one way.

  • Observer Pattern Help

    hi,
    I am trying to understand how and when you would use an observer pattern. I understand that it allows one class to observe another, i.e if a variable was to change in 1 class all observing classes would be notified of the change. I do not understand how u would implement this, I have seen some examples but they are kinda confusing does anybody have a simple way of showing how this pattern is implemented?
    thx
    sbains

    Dish would be the observable in this case. Waiter and Chef are the /
    contain observers. The observer's update method will get called whenever
    the observable calls notifyObservers.
    public class Dish extends Observable {
        public void setStock(int stock) {
            .. business logic ..
            this.setChanged();
            this.notifyObservers(new Integer(stock));
    public class Waiter implements Observer {
        public void update(Observable o, Object arg) {
            Long stock = (Long) arg;
            .. business logic ..
    }Note that Listeners are also implementations of the Observer pattern, if
    that helps any.

  • Variation of Observer pattern

    Hi,
    I'd like to know if there is a common variation of the observer pattern when there is multiple observable object. As an example here is what my register method looks like.
    addListener(EventListener, Event) {}So basically an event listener can register to receive notification of a specific event. Now, I know I'll need a list of EventListener for every Event or something like that but I like to use a standard way of doing it if there is one.
    Thanks
    Francois

    Hi,
    Thanks for the quick answer but I don't think this apply to me.
    I'll try to explain a little more my problem. I have a class watching multiple sensor. An event listener can register to be notified in case of a change of one of the multiple sensor. They have to register to the class that have access to the sensor like that :
    SensorWatcher.addListener(EventListener ev, int sourceSensor);This is different from the normal Java event handling because normally (like the JButton for instance) there is one event source with multiple listener so the listener don't have to specify for which event source they are registering. That's why I cannot use the Observer pattern out of the box.
    For now, I'm using an Hashtable to map the event source and their event listener vector but it doesn't look that nice to me.
    Bye
    Francois

  • 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

  • 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..

  • About observer pattern

    i have some question about the issue of delay time. for example, i have a web base live quote stock system. you know that every time the stock value is changing, once the stock was changed, each clients will update the stock value immediately. If i use observer pattern to apply the system, the subject will montoring the new stock value which is come from other resource, once the new value is updated, it will notify it's observer to update the value. If i have a hundred, a thoursand.. clients/observer which may be stored in a list. then some client will notify immediately and some are not. Is it right? if the concept is right, is there any solution to solve the issues? Thanks.

    Let me know if I understand your question:
    - you mean if your subject notifies all its observers one by one sequentially in the same thread, then the "last in line" will be notified long after the fist one.
    - plus, if one observer takes a long time to process the notification, subsequent observers may not receive their notification before a while.
    Well, yes, this is a known problem. A well-known incarnation is listeners processing event in a single event-dispatching thread in AWT or Swing: if one listener takes a long time to complete processing the notification, then all subsequent listeners do not receive the notification in time; worse all other graphical events are blocked, and the UI display freezes, because even the repaint events are pending the first listener method to return.
    In Swing the way around this is to ask listener classes to observe a convention: complete quickly all listeners methods - if a time-consuming job must be started as part of processing a notification, spawn another thread for it.
    If you don't trust the observers to observe this convention (you may not be the author of all observers code, or your observers are in different JVMs), then you have no option other to spawn multiple threads:
    one thread per observer
    or, a pool of dispatching threads
    or, a pool of dispatching thread with support for timeouts (there is no generic way to reclaim a thread that is timeouting, but you can choose to have a master thread that monitors dispatching threads for timeout and uses the pool as dispatching threads are timeouting).

  • Reverse observer pattern

    hi,
    is it possible to use the reverse of observer pattern
    i.e - observer pattern is described normally as there is 1 subject & many observers.
    So when the subject changes, it notifies the observers. My problem is I only 1 observer but many things change, so when each of the things (subjects ) change I want to call the observer to get the updates.
    Is it possible?
    What if the each subject is run in a thread.?
    Thank you

    is it possible to use the reverse of observer pattern
    i.e - observer pattern is described normally as there
    is 1 subject & many observers.
    So when the subject changes, it notifies the
    observers. My problem is I only 1 observer but many
    things change, so when each of the things (subjects )
    change I want to call the observer to get the
    updates.
    Is it possible?Yes. Rather than have classes A, B, C register as listeners on class D, have class D register itself as a listener on classes A, B, C. Whenever A, B, or C do something, they'll notify all classes observing them (namely D).
    This is not the inverse of observer pattern but rather a different way of utilizing it than what you have described in your question.
    >
    What if the each subject is run in a thread.?
    If classes A, B, C run in separate threads, the pattern implementation does not change too terribly much. Whenever A, B, C do something they will still notify their observers (namely D). But you should realize that since they are multithreaded you may encounter a time when A and B notify D simultaneously. You will need to think about synchronization.

  • Observer pattern example - JMinesweeper

    Hello, I've developed a JMinesweeper desktop game, similar to the one in Windows. The application uses a well known design pattern: Observer Pattern.
    The source code is free for anyone who finds it useful:
    http://sourceforge.net/projects/jminesweepsorin
    My best regards ! :)

    ejp is right in that the "extends Subject<S,D>" is not needed. Thanks, ejp, for pointing this out.
    But when I get rid of "extends Subject<S,D>" (in both places) I still have the "unchecked cast" warning.
    Since posting the original question, I've learnt a few more things:
    (0) That the cast may be unchecked, but the call is not. Thus even if "this" is not of type "S", there is ClassCastException
    as the argument to update is not of the type expected in the concrete observer. This is reassuring. Crazy stuff does not
    happen!
    (1) That I could solve the whole problem with the "getThis()" trick, as explained by Angelika Langer at http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ205 . (Very helpful FAQ altogether.) That is, replace "this" with a call to an abstract method getThis that returns S. In the concrete subject, getThis is implemented in the obvious way: "return this".
    However, using the getThis() trick seems unsatisfactory, as it forces coders of concrete subclasses of Subject to implement a method for no other purpose than to placate the Generic gods. (In truth there is another justification for using a getThis method, which I may go into in an other post.)
    I'm still hoping someone here can post a better solution.
    Cheers,
    Theo
    Edited by: theodore.norvell on Jun 16, 2009 8:13 PM

Maybe you are looking for

  • [Request] RubyTorrent

    http://benclarke.ca/rubytorrent/ RubyTorrentan easy to use torrent creator for Linux/UNIX Features     * Works in CLI mode, optionally with no output at all     * Comes with a GTK2 user interface for those more desktop-oriented     * AJAX HTML user i

  • Playbook Disables my laptop's WIFI

    Just purchased a Playbook and I'm trying to sync music/videos via the desktop software, however everytime I plus my playbook in my wifi gets disabled. Any advice? thanks

  • CAS array internal DNS IP address best practice

    Hi, Just a question about a best practice approach for DNS and CAS arrays. I have an Exchange 2010 Org. I have two CAS/HUB servers and two MBX servers. My external DNS (mail.mycompany.biz) host record points to a public IP address which is NAT'd to t

  • From string to block diagram

    Hi, I need to know how you can translate a string, a formula, to the block diagram. So for instance, if you have G=5+3*lnW, how can you translate the ln to the ln in the block diagram. The formula isn't fixed so I can't make a hard code. Thanks in ad

  • Is there an audio recorder for ipad3 to record for half hour?

    Is there an audio recorder for ipad3 to record for half hour?