Gui design about observer pattern

i have 2 swt components both including a browser component.
they both are instatiated passing a reference to an observable document:
public class ObservableW3CDocument extends java.util.Observable {
  private Document document;
  private String content;
   * Modifications to the document should be mirrored in by notifications to
   * this document observers
   * @param document
  public void setDocument (Document document) {
    this.document = document;
    if(document.getTextContent()!=null) {
      this.content = document.getTextContent();
      System.out.println("Setting content at: "+content);
    this.setChanged();
    notifyObservers(this);
  public void setContent (String content) {
    this.content = content;
    try {
      this.document = DOMUtil.parseHTML(new StringReader(content));
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    this.setChanged();
    notifyObservers(this);
  public void setDocumentAndContent(Document d, String c) {
    this.document = d;
    this.content = c;
    this.setChanged();
    notifyObservers(this);
}both components implements thejava.util.Observer interface: the first one refresh its content when ever a new document is set (that it, the observable document registers it as an observer).
. the other one should apply an xpath query over it and display the result in its embedded browser.
My question: should I have 2 copies of the same document going around?
How can i make all this updating process easier to mantain?

I have a question mysef:
Why do you separate Document and content? Would they ever differ? Would it confuse callers if they did differ?That having been said, within ObservableW3CDocument, you do not have any instances of Document. Instead, you have references to the instance of Document. As such, there is no 'harm' in having multiple references (or in constantly resetting the Document reference). The garbage collector will take care of the actual object when no more valid references exist.
- Saish

Similar Messages

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

  • Confusion about observer design pattern

    Hi all,
    I have a case related to observer design pattern and I feel a bit confusion.
    Suppose there is a gui class which consists of 2 buttons connect and disconnect to the network and a socket class handling these two operations. Then socket class will inform the gui class if the operation is success or not. By applying the observer design pattern. gui class is observer and socket class is obserable. however I feel confusion as observer will send a command e.g. connect to observable.

    dophine wrote:
    my confusion is that the observer is the event source not the listernerIt is an observer but it also takes another role: the controller of the observable.
    kind regards,
    Jos

  • Question about GUI Design on JTable and its separate editor

    Hi all,
    I need to use JTable with separate editor , that way when I double click one of the JTable's row its editor will popup in another window.
    Based on GUI design principles, where should I put the editor, in another tab panel or a JDialog ?
    Any advice would be greatly appreciated.
    Regards,
    Setya

    if you dont have to edit a lot of fields, this will
    be a good solution.
    but if you have many fields, it would be a good thing
    to put a JTabbedPane into the under
    JSplitPane-container ... or to use a JDialog :)Yes, that's the only problem I can think of, if the fields are too many.
    But then, if I have so many fields in one form. I won't put them in a JTable because users will find it cumbersome for having to scroll left and right to see those fields. I believe on this scenario JTable is just not the right component to use.
    Regards,
    Setya

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

  • What are some of your favorite practices in GUI design?

    I saw a conversation a few weeks ago about LVOOP vs Clusters for passing around data that I found fascinating - and quite informative.  I thought I'd try to open up a discussion about GUI design and see what I could learn.
    Edit: to give an example, I have found that I have taken an irrational dislike to tab controls. Instead, I use clusters with a few supporting VIs. Switching the "tab" will just make the proper cluster visible, and the others invisible.  Set each cluster as a type def in the project and just edit that for when I need to change something.  It lets me already have all of my control data bundled, and as a bonus sorts them automatically in Event structures.

    mikeporter wrote:
    So to sum up:
    Tab Controls -- Bad
    Subpanels -- Good
    I wouldn't go that far.  I generally need to be more organized in my block diagram when using tabs, but that doesn't mean they are bad.  Have a state in a state machine for updating each tab.  Then when updating the UI look at which tab the user is on, and only update those UI elements.
    There are other limitations to tabs that frustrate me, like .Net controls sometimes do weird things in tabs.  And some times I would have too many tabs and it starts to add rows which get all kinds of confusing.  In these cases I would hide the tabs and replicate the functionality with a single column listbox which changes the tab value.  But at that point it would be just as easy to insert a different VI into a subpanel.
    Unofficial Forum Rules and Guidelines - Hooovahh - LabVIEW Overlord
    If 10 out of 10 experts in any field say something is bad, you should probably take their opinion seriously.

  • 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

  • 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

  • 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

  • Overloaded radio buttons -- good GUI design?

    I don't know where else to ask this. What do you think about overloading radio buttons with multiple functions? I have made an update to my Interactive Color Wheel that uses this technique. I haven't released it yet, but it is available here:
    * http://r0k.us/rock/Junk/SIHwheel.html
    It offers eight different sorts of 1567 colors and their names. That seemed to me to be way too many radio buttons; there were originally just three sorts and three buttons. I made a second row that contains the five new sorts accessed via two buttons. The sorts on each button are closely related, riffs on a theme if you will. Consecutive clicks on one of these two buttons will rotate through its functions, with the button text and toolTip updated to match its current sort and state.
    I won't try describing more -- just use it, and let me know what you think. Intuitive? Ugly? Bad GUI design? Other comments?

    RichF wrote:
    Don't forget to take Spot, the Magic Color Dog for a walk! I recommend a different sort than the default [alphabetically], but you can change sorts on the fly. (Try [by hue], or one of the three Hilbert sorts.) In fact, Spot isn't stopping you from doing anything. Well, you'd have to have him go really slow to type in a hex color.
    I was really, really amazed how fast Spot can run. With the gauge fully to the right, the timer has a specified delay of 0, so he's running as fast as everything else in the program lets him. There's a LOT going on, yet Spot can traverse all 1567 colors in mere seconds.
    [add] It just occurred to me, maybe I should set a minimum update rate. I don't want it to cause someone to have an epileptic seizure. I'm thinking of setting 10 updates a second as the fastest it would go. What do you guys think?Actually it made me have to kill the JVM to stop the applet (closing the web page didn't work, apparently the new Java plugin sandboxing doesn't work). Only the JList was updating at full speed, not the color wheel.
    This one I did not do. There was a complication with intensity. It uses a quantized color space, with intensity almost ranging from 0..74. I say almost because this integral range also includes 0.5. I forced that in so the value after black on a 0.255 scale would not be 4, but 2. The third value is 4, and the rest of the time it jumps by 3 or 4 on the 255 scale.
    Once I decided to keep the intensity buttons as they were, it did not make sense to change the tile width buttons either. Their range is only 10..15, so IMO the [-] and [+] buttons work well.Just as a demo how to do that with JSpinner (JSlider is much harder to have non linear scales):
    import java.awt.EventQueue;
    import java.awt.FlowLayout;
    import javax.swing.JFrame;
    import javax.swing.JSpinner;
    import javax.swing.SpinnerNumberModel;
    public class TestJSpinner {
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    SpinnerNumberModel rings = new SpinnerNumberModel(10, 10, 15, 1);
                    SpinnerNumberModel intensity = new SpinnerNumberModel(10.0, 0.0, 74.0, 1.0) {
                        @Override
                        public Object getPreviousValue() {
                            Double value = (Double) getValue();
                            if (value == 1.0) {
                                return 0.5;
                            else if (value == 0.5) {
                                return 0.0;
                            else {
                                return super.getPreviousValue();
                        @Override
                        public Object getNextValue() {
                            Double value = (Double) getValue();
                            if (value == 0.0) {
                                return 0.5;
                            else if (value == 0.5) {
                                return 1.0;
                            else {
                                return super.getNextValue();
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame.getContentPane().setLayout(new FlowLayout());
                    frame.getContentPane().add(new JSpinner(intensity));
                    frame.getContentPane().add(new JSpinner(rings));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
    }Edited by: Walter Laan on Nov 5, 2010 2:01 PM

  • Good Java GUI Designer... & UML Eclipse Plugin...

    Hi,
    Im starting my final year project in september & while I have some free time I wanted to get prepared and set up my development environment.
    Im going to be using Eclipse for the IDE which is fine.
    But I need a GUI designer, so I can throw a GUI together quickly so I can get a prototype out for December.
    But I have searched High and Low for one and threre does not seem to be a decent (free) one about Jigloo seems to have problems on my mac and does not seems to be that good.
    Any suggestions?
    Also can anyone recommend and good UML plugin for eclipse?
    Message was edited by:
    ChrisUK

    Why not use Netbeans? I don't think you will find a better GUI builders than Matisse.
    I have used Jigloo, it is okay but I would rather build my GUI in Netbeans and then import my code to Eclipse.
    I have never used any UML plug-ins for Eclipse but I have used Poseidon which is free for non-commercial use and a pretty cool UML designer.
    http://www.gentleware.com/uml-software-community-edition.html
    http://www.netbeans.org/kb/41/flash-matisse.html

  • References on Good GUI Design

    Hi folks,
    I was wondering if anyone out there knew of good resources (ideally a tutorial-style book, not a reference) that would teach me about GUI design - the class structure (mine are always hideously coupled) and general conventions etc....
    I mean, I know how to put together a gui that works, but they are not always code that I am proud of... (blushes)
    Any ideas?
    Thanks!

    Hi folks,
    I was wondering if anyone out there knew of good
    resources (ideally a tutorial-style book, not a
    reference) that would teach me about GUI design - the
    class structure (mine are always hideously coupled)
    and general conventions etc....
    I mean, I know how to put together a gui that works,
    but they are not always code that I am proud of...
    (blushes)
    Any ideas?
    Thanks!Are you asking how code or design GUI?
    if(code) {
       // find "Divelog" tutorial
    } else if(design) {
      // find something about usability engineering
      //ie http://java.sun.com/docs/books/tutorial/networking/TOC.html
    }

  • 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

Maybe you are looking for

  • Problem with my iMac (lion os x)

    A good day I wonder what's wrong with my computer iMac OS X Lion? Everything is working normally, then suddenly occurs to me that the computer stops responding or freezes me in an instant and no key or anything does not work,unresponsive and appears

  • Mod_jk works for JSP but not Servlet

    I have successfully linked Apache to Tomcat using mod_jk and am able to JSP's both on Tomcat and Apache. My servlet runs fine under Tomcat: http://localhost:8080/servlet/HelloWorld but under Apache: http://localhost/servlet/HelloWorld I get "HTTP 404

  • Generating a consumer proxy

    I have reached total frustration. I am trying to generate a service consumer proxy for an external, non-sap web service. I have tried several different web services during testing, and all but the most basic ones failed with a library error, with the

  • Please tell me what is the problem with this code

    Hai, Iam new to Swings. can any one tell what is the problem with this code. I cant see those controls on the frame. please give me the suggestions. I got the frame ,but the controls are not. this is the code: import javax.swing.*; import java.awt.*;

  • What is the best file format for video playback on apple tv?

    I am using winX dvd ripper platinum, so i have a wide range of choices. If I make an exact copy, will it play on apple tv? or do I need to save it in a certain format?