Tuesday, 14 June 2016

Observer Design Pattern- JAVA Implementation

What is Observer Design Pattern?

The observer pattern involves constant observation of a "Subject of interest" (called as Subject) by different stake holders (called as Observers or Subscribers), so that the subscribers can get notified automatically for any state change or update in the subject properties.

Real world example:

Assume that for a bank loan, information are available through Newspaper and Internet. Any change in the rate of interest or name of the loan is published in the Newspaper or Internet.

This is a typical example of Observer Pattern, where the subject is "Loan" and observers/subscribers are "Newspaper" and "Internet"

Implementation using Java.

Classes:
Subject: Abstract class containing the key properties and behaviors for the subject type

Loan: Implements Subject class and has its own properties, like rate of interest, loan name, loan type.

Subscriber: Abstract class containing key properties and behaviors for a subscriber or observer

Internet: One of the subscribers, who implement Subscriber class

Newspaper: One of the subscribers, who implement Subscriber class

ObserverPatternImplementer: It is the main class, which creates the objects and implements the observer pattern

Subject Class:

package org.rajesh.javaconcepts4u.dto;

import java.util.ArrayList;
import java.util.List;

abstract class Subject {

 List<Subscriber> subscriberList = new ArrayList<Subscriber>();


 abstract void addSubscriber(Subscriber subscriber);

 abstract void removeSubscriber(Subscriber subscriber);

 public void notifySubscriber(Subscriber subscriber)
 {

  subscriber.update(this);
 }

 public void notifyAllSubscribers(){
 

 
  for(Subscriber subscriber:subscriberList)
  {
  
   subscriber.update(this);
  }
 
 }


}


Loan Class:

package org.rajesh.javaconcepts4u.dto;

public class Loan extends Subject {
 private String loanName;
 private String type ;
 private int rateOfInterest;


 public String getLoanName() {
  return loanName;
 }
 public void setLoanName(String loanName) {
  this.loanName = loanName;
  notifyAllSubscribers();
 }
 public String getType() {
  return type;
 }
 public void setType(String type) {
  this.type = type;
  notifyAllSubscribers();
 }
 public int getRateOfInterest() {
  return rateOfInterest;
 }
 public void setRateOfInterest(int rateOfInterest) {
  this.rateOfInterest = rateOfInterest;
  notifyAllSubscribers();
 }

 @Override
 public void addSubscriber(Subscriber subscriber) {
 
  subscriberList.add(subscriber);
  notifySubscriber(subscriber);

 }
 @Override
 public void removeSubscriber(Subscriber subscriber) {
  subscriberList.remove(subscriber); 
 
 }


 @Override
 public String toString() {

  return getType()+ " : "+ getLoanName() + " has rate of interest of "+getRateOfInterest();
 }


  

}

Subscriber Class:

package org.rajesh.javaconcepts4u.dto;

public abstract class Subscriber {

 protected Subject subject;


 
 public Subject getSubject() {
  return subject;
 }

 public void setSubject(Subject subject) {
  this.subject = subject;
 }

 abstract void update(Subject subject);



}

Internet Class:

package org.rajesh.javaconcepts4u.dto;

public class Internet extends Subscriber{

 @Override
 void update(Subject subject) {
  this.subject = subject;
 
  System.out.println("Internet feed received: "+ subject);
 
 }



}

Newspaper Class:

package org.rajesh.javaconcepts4u.dto;

public class Newspaper extends Subscriber{


 @Override
 void update(Subject subject) {
  this.subject = subject;
  System.out.println("Newspaper feed received: "+ this.subject);
 
 }

   
}

ObserverPatternImplementer Class:

package org.rajesh.javaconcepts4u.main;

import org.rajesh.javaconcepts4u.dto.Internet;
import org.rajesh.javaconcepts4u.dto.Loan;
import org.rajesh.javaconcepts4u.dto.Newspaper;
import org.rajesh.javaconcepts4u.dto.Subscriber;

public class ObserverPatternImplementer {

 public static void main(String[] args) {
  // Created loan object
  Loan loan = new Loan();
  loan.setLoanName("Easy Home Loan");
  loan.setType("Home Loan");
  loan.setRateOfInterest(10);
 
  //Created Subscribers
  Subscriber newspaper = new Newspaper();
  Subscriber internet = new Internet();
 
  //Configuring the Subscribers to observe loan
  newspaper.setSubject(loan);
  internet.setSubject(loan);
 
  //adding the subscribers to observe the subject/loan
  System.out.println("Newpaper subscriber added");
  loan.addSubscriber(newspaper);
  System.out.println("Internet subscriber added");
  loan.addSubscriber(internet);
 
  //Changing loan interest rate
  System.out.println("Changing the rate of interest rate from 10 to 8 ");
  loan.setRateOfInterest(8);
 
 
 }

}

Sample Output:

Newpaper subscriber added
Newspaper feed received: Home Loan : Easy Home Loan has rate of interest of 10
Internet subscriber added
Internet feed received: Home Loan : Easy Home Loan has rate of interest of 10
Changing the rate of interest rate from 10 to 8 
Newspaper feed received: Home Loan : Easy Home Loan has rate of interest of 8
Internet feed received: Home Loan : Easy Home Loan has rate of interest of 8


Note: Please share your comments and feedbacks


Friday, 20 December 2013

Some Intelligent Questions By my blog followers



Some Intelligent Questions By my blog followers

1. String s1 = new String("Hello");
how does this thing work in memory. i.e. First the "Hello" object is created and then its reference is passed to the string s1 variable. But how can a constructor return something when it cannot return anything?
Ans: Following steps are executed for the above statement:

1. Argument String -"Hello" is created
2. ***A new String Object is created by the keyword "new" and string object reference is assigned to s1
3. The value and hash of the argument string is assigned to the new string created in step 2

Please note: we should understand how "new" keyword works to understand how an object is created.
The below example would help us understand the work of new keyword:
class A {
// ...
new B();
// ...
}

Is this equivalent to

class A {
// ...
A.class.getClassLoader().loadClass("B's canonical name").newInstance();
// ...
}

The newInstance() method returns an object of loadClass type.
***So I our case it creates a String object and assigns it to s1.

2. String class is Final that's y Strings are immutable. This was the concept behind Immutability. Please can you explain y is String Buffer Thread safe and String Builder NOT.. ?
Ans: First of all I would like to highlight the concept of have Strings as "Immutable".
If you follow my string tutorials you will understand that JVM does not create String every time it gets a new request, but it looks for the same in the string pool. If it is available, then it returns the String object from the pool else let it proceeds in creating a new String.
Now, if you think -Strings were "mutable" then it would have been a catastrophe. Anyone can play with the String you created and you would be guessing how your String values are changing!!

Now I come to your question: Why StringBuffer is threadsafe while StringBuilder is not?
I hope you have understood that why there is the requirement of mutable sequence of character class. For this reason Java provides two versions of mutable sequence of character classes:

  1. StringBuffer- a thread safe, mutable sequence of character class, since JDK 1.0
  2. StringBuilder- mutable sequence of character class, since JDK 1.5

Now why StringBuffer is thread safe and why there was a new requirement for a non- thread safe version of StringBuffer – StringBuilder?
The reason for making StringBuffer thread safe is pretty straight forward, ie: to use a StringBuffer object by several threads without any problem. Its methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.
So, we had our solutions for mutable class which is thread safe, but why again non-thread safe StringBuilder?
The reason for having a non-thread safe StringBuilder class is for replacement of StringBuffer class where ever string buffer was being used by single thread (as in most of the cases). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be much faster under most implementations.
3. Its always the reference which is set to variables, y java does not work on assigning values directly to variables.... y it always refer to variables whereas in other languages we can directly assign values to variables .. this will consume less space (i.e. Variables & reference Object spaces individually).. ?
Ans: In all high level languages there are always two memory sections blocked for every successful initialization of a variable –
a. Memory location where the value is stored
b. Memory location where the reference to the value is stored
so, if we have a statement like
int i= 5;
  1. A new integer object with value 5 is created and stored in a memory location
  2. A reference to the new object is created (i) and stored in another memory location and which points to the integer object having value= 5
  3.  
We say in Java, that an integer Object i is created with value 5. But actually the above two steps (a,b) are executed in all high level programming languages.
In certain languages like C we can access the memory location of the reference variable but is JAVA this is not permitted.


Sunday, 18 August 2013

Core Java Concepts: Strings & Memory

Visit My Page in TutorIndia.net
Core Java Concepts: Strings & Memory


Strings & Memory

# Key Points
>>Java sets aside a special area in memory called the "String constant pool"
>>Several reference variables refer to the same string object without knowing about each other thus  this is the reason why string objects are made "Immutable"
>>String class is final so that nobody can override it

One of the key goals of any good programming language is to make efficient use of memory.
As applications grow, it`s very common for String literals to occupy large amounts of a program`s memory, and there is often a lot of redundancy within the universe of String literals for a program. To make Java more memory efficient, the
JVM sets aside a special area of memory called the "String constant pool."

When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created.


Now we can start to see why making String objects
immutable is such a good idea. If several reference variables refer to the same String without even knowing it, it would be very bad if any of them could change the String`s value.


Sunday, 21 July 2013

String Class in JAVA and their Immutable Property

Visit My Page in TutorIndia.net
Core Java Concepts String Tutorial Part1

    
String Class in JAVA and their Immutable Property

# The String Class

This section covers the String class, and the key concept to understand is that once a String object is created, it can never be changed-so what is happening when a String object seems to be changing? Let`s find out.

# Keys Points:
> Each character is a16-bit Unicode character
> Strings are Objects in Java
> String Objects are immutable: Once a String object is created, it can never be changed


# Strings Are Immutable Objects

Let us create String Object
String s = new String();

This line of code creates a new object of class String, and assigns it to the reference variable s. So far, String objects seem just like other objects. Now, let`s give the String a value:

s = "abcdef";

As you might expect, the String class has about a zillion constructors, so you can use a more efficient shortcut:
String s = new String("abcdef");

And just because you`ll use strings all the time, you can even say this:
String s = "abcdef";

There are some subtle differences between these options that we`ll discuss later,but what they have in common is that they all create a new String object, with a value of "abcdef", and assign it to a reference variable s. Now let`s say that you want a second reference to the String object referred to by s:

String s2 = s; // refer s2 to the same String as s

So far so good. String objects seem to be behaving just like other objects, so what`s all the fuss about?.Immutability!

(What the heck is immutability?)
>>Once you have assigned a String a value, that value can never change- it`s immutable, frozen solid, won`t budge, fini, done.

The good news is that while the String object is immutable, its reference variable is not, so to continue with our previous example:

s = s.concat(" more stuff"); // the concat() method `appends`
                             // a literal to the end

Now wait just a minute, didn`t we just say that Strings were immutable? So what`s all this "appending to the end of the string" talk? Excellent question: let`s look at what really happened.

The VM took the value of String s (which was "abcdef"), and tacked " more stuff" onto the end, giving us the value "abcdef more stuff".

Since Strings are immutable, the VM couldn`t stuff this new value into the old String referenced by s, so it created a new String object, gave it the value "abcdef more stuff", and made s refer to it.

At this point in our example, we have two String objects: the
first one we created, with the value "abcdef", and the second one with the value "abcdef more stuff".

Technically there are now three String objects, because
the literal argument to concat, " more stuff", is itself a new String object. But we have references only to "abcdef" (referenced by s2) and "abcdef more stuff" (referenced by s).

What if we didn`t have the foresight or luck to create a second reference variable for the "abcdef" String before we called s = s.concat(" more stuff");? In that case, the original, unchanged String containing "abcdef" would still exist in memory, but it would be considered "lost."

No code in our program has any way to reference it-it is lost to us. Note, however, that the original "abcdef" String didn`t change (it can`t, remember, it`s immutable); only the reference variable s was changed, so that it would refer to a different String.

For more video tutorial please visit:
http://www.youtube.com/channel/UCI6PEB8D4Hfe9ZmfiX3JeOw

Wednesday, 17 July 2013

Welcome to JavaConcepts4U!

Welcome to JavaConcepts4U!
Here we will deal with some specific concepts of the following:

Core Java, JSP, Servlets, Basic MVC Frameworks, Strus 2 framewok related concepts, Hibernte, Spring, Maven, Web Services and many more...

We will see these concepts in videos, so whenever you need to refer you can just click and revise your concepts...

So, enjoy these tutorials and do give your valuable feedbacks...

Hope you find things interesting.

Visit My Page in TutorIndia.net