Solved

what is an Observer pattern ?

Posted on 2006-07-07
10
659 Views
Last Modified: 2011-10-03
what is an Observer pattern ?

please explain  with  a simple example.

though i have seen some tuts but it seems observers observes the subjects.....may be in multithreading enviornment an observer is responsible whats happening or status of the individual threds.

BTW, i am looking for an example......i have seen some example from the net but not satisfied.
looking for a nice  example...can you help ?
0
Comment
Question by:cofactor
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 35

Assisted Solution

by:girionis
girionis earned 35 total points
Comment Utility
Think about a BankAccount that belongs to someone who is a bad payer. Then think about the manager in the bank that he wants to observe the account and be notified when the money in the account go below a credit limit. What you have to do is to register the manager with the bank account and notify him when the credit changes.

The BankAccount (which is usualyl called "the subject") is something like:

public class BankAccount extends Observable
{
   double amount = ...;

   public double getCredit()
   {
      return amount;
   }

  public void setCredit(double amount)
  {
     this.amount = amount;
     if (this.amount < limit)
         notifyObeservers(new Double(this.amount));  // Here you notify the manager who is watching the account that the amount has changed.
  }
}

and the manager class

public class BankManager implements Observer
{
...
  // The manager is notified here when the account goes below the limit
  public void update(Observable obs, Object arg)
  {
       System.out.println("the acount is below the limit. It has: " + ((Double) arg).doubleValue() + " credit");
  }
}

Of course before you use it you have to register the manager to the bank account to listen for changes:

BankManager manager = new BankManager();
BankAccount account = new BankAccount();
account.addObserver(manager);
0
 

Author Comment

by:cofactor
Comment Utility
>Think about a BankAccount that belongs to someone who is a bad payer

is it a loan account ? the payer has to pay ? or savings account ?
i guess its a loan account ....because you are saying "bad payer"


>he wants to observe the account and be notified when the money in the account go below a >credit limit

what do  u mean by below credit ? say the payer paid 3 months  but did not pay the  next 3 months ....so do you mean thats a below credit for the bank account ?

please explain a bit .
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
cofactor,

> i guess its a loan account ....because you are saying "bad payer"

It does not matter :) For the sake of clarity think about *any* bank acount. The manager wants to know if the credit has gone below zero and if it has, then he needs to send a reminding letter to the customer.
0
 

Author Comment

by:cofactor
Comment Utility
your  code looks interesting.....i know its a pseudocode

however i would like to ask few questions on your code.

here are those...

Q1.>public class BankAccount extends Observable

is this class  *observable*  defined in the java API ?  or its a mere class that developer have to code ?


Q2>public class BankManager implements Observer

same question for *observer* too.

Q3>see, you have   *notifyObeservers(new Double(this.amount));* which notifies manager....  but  this  method is not present in the BankManager class....did you forget it to code in the BankManager class ?

0
 
LVL 16

Accepted Solution

by:
imladris earned 25 total points
Comment Utility
girionis seems to be offline for the moment, so I'll fill in for a while.

>Q1.>public class BankAccount extends Observable

>is this class  *observable*  defined in the java API ?  or its a mere class that developer have to code ?

Yes. It is a class (that extends Object) defined in the util package.

Q2>public class BankManager implements Observer

same question for *observer* too.

Yes. It is an interface defined in the util package.

>Q3>see, you have   *notifyObeservers(new Double(this.amount));* which notifies manager....  but  this  method is not present in the BankManager class....did you forget it to code in the BankManager class ?

No. The notifyObservers call (supplied by the Observable class) will look for any observers, and then, for each one it finds, call their update method (required by the Observer interface).

Note that the real power of this paradigm lies in situations where you have a varying number of Observers. Here imagine, for instance, that there is another class observing the bank account that does security checks. That is, if a transaction is larger than a defined amount, it ensures that the profile of the customer matches certain criteria. And that there is a third observer, which may or may not be running, that is managing a contest (in the vein of, if you deposit more than a $100.00 you could win a house!). The BankAccount object does not need to change or even be aware of, the number of observers running. So observers can be added and removed with relative ease.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:cofactor
Comment Utility
thanks for the nice input.
you told..(though this is really not important but just to make sure..)
>. That is, if a transaction is larger than a defined amount, it ensures that the profile of the >customer matches certain criteria.

whats that security check ?  i dont  know really bacnk checks anything like that ....of course  if you are transacting more than available in your debit account, then you will get some error message in the internet banking.

BTW, really bank does match   certain criteria ? why ?

again this is not java question though.

It seems bankng applications are more robust and complex.....so many checks....so many observers...

but your explanation is nice to read.

thanks
0
 
LVL 10

Expert Comment

by:mukundha_expert
Comment Utility
Observer pattern _ One more Example

Consider a Shopping Cart UI, you have a panel diplaying the items in the shoppingcart.
you have ShoppingCart class which holds list of items in the cart.
your panel gets items list from the ShoppingCart object and displays it,

Normally what we would do is when ever a user adds an item to the shoppingList we could call the status changed on the shopingList panel to show the updated shoppingList.

Lets see how we can do it using Observer pattern,

make the ShoppingList class extends Observable
and your UI panel implements Observer

add observer to shoppingList class ( Observable) --   addObserver ( ur Panel )

Now if the customer adds an item to the shoppingList ( the observable) , you will notify the observer about your event ( here it is your panel),

so in the panel you can get the event details and display the updated items list.


U might not be able to appreciate Observer pattern for this scenario since there is a single observer and u might ask why should you do that??

But assume the real scenario, when ever the customer adds the item,

-->UI has to update the display
-->You have to compute the total price ( suppose in a different class )
-->Update your store database
-->compute the loyalty points for the customer
--> ...
..


what you can do is make all these action classes observer for the ShoppingList ( observable ),

so you no need to call the methods on these classes ( like status changed(), itemAdded() ... ) instead you will add them as observer,

there can be any number of observers for a observable object,

so in future if you decide to add one more action to your shoppingcart application for addingItem ( writing the new item to a file ),
you can create a new action class for that and make it observer for the shoppinglist. so your data holder shoppinglist will remain independent of the observers. so you need not modify it when ever you decide to add more actions
0
 
LVL 16

Expert Comment

by:imladris
Comment Utility
>BTW, really bank does match   certain criteria ? why ?

I don't really know how banks operate internally, no. It is just an example of what could be done.

One thing I know about a bank I deal with is that signatures on checks are normally not actually checked. They only (manually) actually check signatures if the check is over a certain "limit". If the check is for an amount below that limit, and the signature turns out to be invalid, then they eat the cost. This is cheaper for them than expending the labour to visually verify every signature on every check they clear.

0
 
LVL 16

Expert Comment

by:imladris
Comment Utility
Did any of that help?

If so, it is now time to choose an answer and grade it.

If not, perhaps a clarifying question would help.
0
 

Author Comment

by:cofactor
Comment Utility
yes...sorry....i was bit busy  in the meantime.....i  want  share the points  imaldris and  girionis
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now