Using observer pattern (NSNotificationCenter) accross threads [iPhone]

On my main thread I register an observer for the NSNotificationCenter defaultCenter.
I then start a background process via [self performSelectorInBackground...].
The idea is that the background threas fires a notification (using defaultCenter, too) to inform the "calling/main" thread once it has finished.
However, the event seems to never arrive at the main thread.
Any hints?
Do I have to create kind of a shared Notification Center???

Sounds like you've laid out your problem quite well.
You could use a fifo queue (producer-consumer queue) per thread - basically receiveResponse would check to see if there is anything in its (response) queue - if so, it is removed, if not, it waits. The socket thread receives a packet, finds the appropriate queue and pushes in the response - which wakes the receiver. This is thread safe, if done correctly - it is easy to do correctly.
Now that I think about it more, your queue can only store one element, given the request/response nature of the communication, so you don't even need to use a collection.
As for patterns, I think that Pattern Oriented Software Architecture Volume 2 (http://www.cs.wustl.edu/~schmidt/POSA/) may be of interest. And if threading and concurrency are of interest, checkout Concurrent Programming in Java, Doug Lea (http://www.amazon.com/exec/obidos/ASIN/0201310090/)

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

  • Helping , Observable's multithread problem, thread is losting ?

    i am practicing an example of Observable and Observer pattern. But one problem were occured as following:
    the programe will print out a 10*10 grid , and using observer pattern to change every grid 's color.
    The fill rule is that : 1. randomly to choose a beging grid,
    2. notify the four grid (left ,right , upper, below of the choosed grid) to change their's grid color.
    The problem is when using multithread to notify grid , not all of the grid will be changed color, but if using single thread to notify grid, then all of the grid will be notified, and color changed.
    the switch of the multithread and single thread is the P.java 's 62-66 line, and 67-71 line, the source is following, anyone can help to analysing the source, and found exactly where is reason of not all of the grids could be notified , very thanks.
    the starup class is the Guess10.java.
    the source :
    package guess10:
    package guess10;
    import java.util.*;
    import guess10.gui.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2005</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class P
        implements Observer {
      public P() {
      public P(int x, int y) {
        this.x = x;
        this.y = y;
      public static void main(String[] args) {
        P p1 = new P();
      int x;
      int y;
      public void open() {
    //    System.out.println("open " + this);
      public void update() {
    //    System.out.println("update " + this);
    //    System.out.println("[" + x + "," + y+"]");
        F.instance.getGrid(x, y).action();
      public void open(Observable ob) {
        open();
    //    System.out.println(this);
        ob.deleteObserver(this);
      public void update(final Observable ob) {
        update();
        ( (PObservable) ob).change();
    //    ob.notifyObservers(new Point[]{new Point(x+1,y)});
    //    ob.notifyObservers(new Point[]{new Point(x,y+1)});
    //    ob.notifyObservers(new Point[]{new Point(x+1,y+1)});
    //    ob.notifyObservers(new Point[]{new Point(x-1,y-1),new Point(x+1,y-1),
    //    new Point(x+1,y+1),new Point(x-1,y+1)});
          final Point[] p = new Point[] {
              new Point(x - 1, y), new Point(x, y - 1),
              new Point(x + 1, y), new Point(x, y + 1)
         new Thread(new java.lang.Runnable() {
            public void run() {
                ob.notifyObservers(p);
          },"" + x +"," + y ).start();
    //      new java.lang.Runnable() {
    //        public void run() {
    //          ob.notifyObservers(p);
    //      }.run();
      public void update(Observable observable, Object object) {
    //    System.out.println(this+" " +Thread.currentThread().getName());
        Point[] p = (Point[]) object;
        for (int i = 0; i < p.length; i++) {
            if (this.x == p.x && this.y == p[i].y) {
    if ( ( (PObservable) observable).exist(this)) {
    open(observable);
    update(observable);
    public static int count = 0;
    public String toString() {
    return "x = " + x + " y = " + y;
    // now not used
    private Object lock = new Object();
    package guess10;
    import java.util.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2005</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class PLayout {
    private BitSet xb = new BitSet();
    private BitSet yb = new BitSet();
    PObservable o = new PObservable();
    public PLayout() {
    public static void main(String[] args) {
    PLayout PLayout1 = new PLayout();
    * create 100 p object, and store into Observable object
    public void init() {
    for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
    P p = new P(i, j);
    o.addObserver(p);
    // todo : need to subclass for the Observable ??
    // otherwise , how to set changed to true ?
    public void start(int x, int y) {
    o.change();
    o.notifyObservers(new Point[] {new Point(x, y)});
    package guess10;
    import java.util.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2005</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class PObservable
    extends Observable {
    public PObservable() {
    super();
    public static void main(String[] args) {
    PObservable PObservable1 = new PObservable();
    public synchronized void change() {
    this.setChanged();
    public synchronized boolean exist(P p) {
    return v.contains(p);
    private Vector v = new Vector();
    public synchronized void addObserver(Observer o) {
    super.addObserver(o);
    v.add(o);
    public synchronized void deleteObserver(Observer o) {
    super.deleteObserver(o);
    v.remove(o);
    package guess10;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2005</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class Point {
    public Point() {
    public Point(int x, int y) {
    this.x = x;
    this.y = y;
    public static void main(String[] args) {
    Point point1 = new Point();
    int x;
    int y;
    package guess10;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2005</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class Guess10 {
    public Guess10() {
    public static void main(String[] args) {
    Guess10 guess101 = new Guess10();
    guess101.start();
    public void start() {
    PLayout pl = new PLayout();
    pl.init();
    int x = 0;
    int y = 0;
    java.util.Random random = new java.util.Random(System.currentTimeMillis());
    x = random.nextInt(10);
    y = random.nextInt(10);
    pl.start(x, y);
    // try {
    // x = System.in.read();
    // y = System.in.read();
    // catch (IOException ex) {
    // ex.printStackTrace();
    // if(!isDigit(x) | !isDigit(y)) {
    // System.out.println("Not correct number! " + x + " " + y);
    // System.exit(1);
    // pl.start(x-'0',y-'0');
    static boolean isDigit(int ch) {
    return ( (ch - '0') | ('9' - ch)) >= 0;
    package guess10;
    import java.io.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2005</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class Out {
    public Out() {
    public static void main(String[] args) {
    Out out1 = new Out();
    public static final PrintStream out = System.out;
    public static void print(PLayout playout) {
    the package guess10.gui
    package guess10.gui;
    import java.awt.*;
    import javax.swing.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2005</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class F
    extends JFrame {
    public static F instance = new F();
    public F() {
    super("O G");
    init();
    setVisible(true);
    private Grid[] ps = new Grid[100];
    public Grid getGrid(int x, int y) {
    return ps[x * 10 + y];
    public void init() {
    Container con = this.getContentPane();
    con.setLayout(new java.awt.GridLayout(10, 10));
    for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
    con.add(ps[i * 10 + j] = new Grid());
    setSize(400, 400);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public static void main(String[] args) {
    F f1 = new F();
    f1.getGrid(4, 3).setBackground(Color.yellow);
    package guess10.gui;
    import java.awt.*;
    import javax.swing.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2005</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class Grid
    extends JPanel {
    public Grid() {
    super();
    this.setBorder(BorderFactory.createEtchedBorder());
    // this.add(new javax.swing.JTextField("777"));
    public static void main(String[] args) {
    Grid grid1 = new Grid();
    public void action() {
    try {
    Thread.currentThread().sleep(100);
    catch (InterruptedException ex) {
    // this.setBackground(Color.yellow);
    this.setBackground(new Color(r--, g--, b++));
    // add(new javax.swing.JLabel(Thread.currentThread().getName()+" "+count++));
    // this.validate();
    private static int r = 255;
    private static int g = 230;
    private static int b = 128;
    private static int count = 0;

    copy the java file into notepad, and save to .java file,
    then javac guess10\*.java file to compile, and java guess.Guess10 to run , then can see the gui's output,
    Only you see the gui's output, you can understand what i describe.
    Only seeing the source will not found the reason of the problem, it's need to run indeedly.
    is there anyone to try that ?

  • 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

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

  • I am trying to use Words with friends on my iphone 5.  How do I get rid of   "Connect to itunes to Use Push Notifications

    I am trying to use Words with friends on my iphone 5.  How do I get rid of   "Connect to itunes to Use Push Notifications

    Reading some older threads from 2012 and 2011 it appears the problem was present even then.  Part of the problem was due to people using multiple or different account id's on the various devices.  In my case, I only have one ID and it is the same on all devices yet the iPhone and iPad are still throwing the same error when I try turning on iTunes Match.  This is very frustrating . . . any help out there?  Thanks.

  • How can I be using so much data on my iPhone 5

    How can I possibly be using so much data on my iPhone. I usually listen to Pandora for about an Hour each day I drive to work. So far (the first 8 days of my billing cycle I have used about 1 GB of data. According to Verizon's calculations I based on this usage I should be using a total of about 1.5 GB of data/month. I called both Verizon and Apple and received no resolution. Apple confirmed that the Phone's wifi shuts off WIFI when the phone is asleep. Resulting in the phone switching to LTE. Apple also indicated that apps that are in the background tend to use data as well. This still doesn't make sense. I had the same data usage pattern (Pandora) with my old 3GS and only used about 1GB/ month. There has got to be another solution. I refuse to believe that just using Pandora for about an hour/day for 5/days a week results in a GB of data usage. Any suggestions?

    So, I thought itunes match (like Pandora) streams music from the cloud. I didn't think that the phone 'syncs' several times a day. I did notice a pattern between 11am-1pm data being used in the order of 29 mb yesterday, 42 mb the day before, and 43 mb the day before that. This is at a time when I know I am not using any significant data on my phone. Yesterday I even closed all my apps w/the exception of Pandora which I made sure wasn't running during the day. This additional usage can easily add up to the 100 mb/day i'm averaging.

  • Can you use the same charging cable for both an iPhone and an IPad or are they different?  When I use the charging cable for my iPhone on my Ipad, it doesn't charge.

    Can you use the same charging cable for both an iPhone and an IPad or are they different?  When I use the charging cable for my iPhone on my Ipad, it doesn't charge.

    The quickest way (and really the only way) to charge your iPad is with the included 10W USB Power Adapter. iPad will also charge, although more slowly, when attached to a computer with a high-power USB port (many recent Mac computers) or with an iPhone Power Adapter (5W). When attached to a computer via a standard USB port (most PCs or older Mac computers) iPad will charge very slowly (but iPad indicates not charging). Make sure your computer is on while charging iPad via USB. If iPad is connected to a computer that’s turned off or is in sleep or standby mode, the iPad battery will continue to drain.
    Apple recommends that once a month you let the iPad fully discharge & then recharge to 100%.
    How to Calibrate Your Mac, iPhone, or iPad Battery
    http://www.macblend.com/how-to-calibrate-your-mac-iphone-or-ipad-battery/
    At this link http://www.tomshardware.com/reviews/galaxy-tab-android-tablet,3014-11.html , tests show that the iPad 2 battery (25 watt-hours) will charge to 90% in 3 hours 1 minute. It will charge to 100% in 4 hours 2 minutes. The new iPad has a larger capacity battery (42 watt-hours), so using the 10W charger will obviously take longer. If you are using your iPad while charging, it will take even longer. It's best to turn your new iPad OFF and charge over night. Also look at The iPad's charging challenge explained http://www.macworld.com/article/1150356/ipadcharging.html
    Also, if you have a 3rd generation iPad, look at
    Apple: iPad Battery Nothing to Get Charged Up About
    http://allthingsd.com/20120327/apple-ipad-battery-nothing-to-get-charged-up-abou t/
    Apple Explains New iPad's Continued Charging Beyond 100% Battery Level
    http://www.macrumors.com/2012/03/27/apple-explains-new-ipads-continued-charging- beyond-100-battery-level/
    New iPad Takes Much Longer to Charge Than iPad 2
    http://www.iphonehacks.com/2012/03/new-ipad-takes-much-longer-to-charge-than-ipa d-2.html
    Apple Batteries - iPad http://www.apple.com/batteries/ipad.html
    Extend iPad Battery Life (Look at pjl123 comment)
    https://discussions.apple.com/thread/3921324?tstart=30
    New iPad Slow to Recharge, Barely Charges During Use
    http://www.pcworld.com/article/252326/new_ipad_slow_to_recharge_barely_charges_d uring_use.html
    Tips About Charging for New iPad 3
    http://goodscool-electronics.blogspot.com/2012/04/tips-about-charging-for-new-ip ad-3.html
    Prolong battery lifespan for iPad / iPad 2 / iPad 3: charging tips
    http://thehowto.wikidot.com/prolong-battery-lifespan-for-ipad
     Cheers, Tom

  • Slow WI-FI transfer using native YouTube application on the iPhone 3G

    Hello all,
    I have seen several posts similar to the one that I'm making now, but since my newest discovery brings a small twist to the issue when compared to the other cases, I decided to make a new thread.
    My issue is with the native YouTube application for the iPhone 3G, as it is mysteriously slow. A lot of people mention that lowering the router to B/G standards will remedy the issue. However, I do not think this issue is related to this because when I launch Safari on the iPhone and go to apple.com/trailers the speed is lightning fast. I did some WI-FI comparison testing:
    PC: XP Pro SP3 running all drivers at newest releases incl. updating motherboard firmware.
    iPhone 3G: Firmware v2.1
    Connection: 10 Mbit/2 Mbit
    Safari cookies, history, and cache cleared after each attempt on both iPhone and PC. Also, I closed Safari, ran CCleaner (just to make sure all temporary data was gone), and reopened Safari on the PC while Powercycling the iPhone 3G between each attempt.
    Movie: http://www.youtube.com/watch?v=psYClvuONG4
    Length: 1 min. 45 sec.
    Load time on PC using Safari: roughly 25 sec.
    Load time on iPhone using Safari: roughly 4 (FOUR!) min. 30 sec.
    After this I directed Safari on both iPhone and PC at:
    Movie: http://www.apple.com/trailers/magnolia/splinter/
    Length: 1 min. 38 sec.
    Load time on PC using Safari: roughly 5 sec. (for the small size as iPhone format does not seem to be available when browsing with a PC)
    Load time on iPhone using Safari: Roughly 10 sec.
    I do not know what is going on here. Do the size and/or compression of the two movie formats differ so much from each other that this could explain the normal transfer speed via apple.com/trailers? Or is there an issue with the YouTube application? Maybe the YouTube conversion system? Could it be a routing and/or hardware (on either ISP, ISP carrier or YouTube itself) issue in case there are "localized portals" for YouTube depending on the user's geographical location?
    In general, speed is not an issue. Performing speed tests towards a localized server in Denmark using my iPhone give excellent results compared to the connection speed I am paying for, and I do not have issues surfing elsewhere via the iPhone. It is only when I use the native YouTube application on iPhone 3G that my transfer rates are poor.
    I really want to solve this problem before I go nuts...
    Best regards

    About a week ago YouTube stopped connecting on my iPhone 3G -- as far as I know nothing changed on my end. The YouTube application seems to function normally, bookmarked videos are still there and play, for example, but it will not update, not search, etc. I get a message that YouTube is not available.

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

Maybe you are looking for