Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

what is an Observer pattern ?

Posted on 2006-07-07
10
Medium Priority
?
743 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 35

Assisted Solution

by:girionis
girionis earned 140 total points
ID: 17057669
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
ID: 17057722
>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
ID: 17057740
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
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 

Author Comment

by:cofactor
ID: 17058385
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 100 total points
ID: 17060691
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
 

Author Comment

by:cofactor
ID: 17063602
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
ID: 17063825
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
ID: 17082182
>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
ID: 17091468
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
ID: 17131106
yes...sorry....i was bit busy  in the meantime.....i  want  share the points  imaldris and  girionis
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

688 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