Sunday 27 February 2011

Abstract factory pattern

This pattern is one level of abstraction higher than factory pattern. This means that the abstract factory returns the factory of classes. Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the subclasses.
Let’s understand this pattern with the help of an example.
Suppose we need to get the specification of various parts of a computer based on which work the computer will be used for.
The different parts of computer are, say Monitor, RAM and Processor. The different types of computers are PC, Workstation and Server.
So, here we have an abstract base class Computer.

 

package creational.abstractfactory; 

public abstract class Computer {

public abstract Parts getRAM();
public abstract Parts getProcessor();
public abstract Parts getMonitor();

}




This class, as you can see, has three methods all returning different parts of computer. They all return a method called Parts. The specification of Parts will be different for different types of computers. Let’s have a look at the class Parts.



package creational.abstractfactory; 
public class Parts {

public String specification;
public Parts(String specification) {
this.specification = specification;
}

public String getSpecification() {
return specification;
}

}// End of class




And now lets go to the sub-classes of Computer. They are PC, Workstation and Server.



package creational.abstractfactory; 
public class PC extends Computer {

public Parts getRAM() {
return new Parts("512 MB");
}
public Parts getProcessor() {
return new Parts("Celeron");
}

public Parts getMonitor() {
return new Parts("15 inches");
}
}




package creational.abstractfactory;

public class Workstation extends Computer {

public Parts getRAM() {
return new Parts("1 GB");
}
public Parts getProcessor() {
return new Parts("Intel P 3");
}

public Parts getMonitor() {
return new Parts("19 inches");
}
}




package creational.abstractfactory; 
public class Server extends Computer{

public Parts getRAM() {
return new Parts("4 GB");
}
public Parts getProcessor() {
return new Parts("Intel P 4");
}

public Parts getMonitor() {
return new Parts("17 inches");
}
}




Now let’s have a look at the Abstract factory which returns a factory “Computer”. We call the class ComputerType.

package creational.abstractfactory;
public class ComputerType {
private Computer comp; public static void main(String[] args) {
ComputerType type = new ComputerType(); Computer computer = type.getComputer("Server");
System.out.println("Monitor: "+computer.getMonitor().getSpecification());
System.out.println("RAM: "+computer.getRAM().getSpecification());
System.out.println("Processor: "+computer.getProcessor().getSpecification());
}

public Computer getComputer(String computerType) {
if (computerType.equals("PC"))
comp = new PC();
else if(computerType.equals("Workstation"))
comp = new Workstation();
else if(computerType.equals("Server"))
comp = new Server(); return comp;

}
}




Running this class gives the output as this:
Monitor: 17 inches
RAM: 4 GB
Processor: Intel P 4.

 

When to use Abstract Factory Pattern?
One of the main advantages of Abstract Factory Pattern is that it isolates the concrete classes that are generated. The names of actual implementing classes are not needed to be known at the client side. Because of the isolation, you can change the implementation from one factory to another.

Decorator pattern examples

Example 1. Instantiating I/O decorators

FileReader       frdr = new FileReader(filename);
LineNumberReader lrdr = new LineNumberReader(frdr);



The preceding code creates a reader -- lrdr -- that reads from a file and tracks line numbers. Line 1 creates a file reader (frdr), and line 2 adds line-number tracking.

At runtime, decorators forward method calls to the objects they decorate. For example, in the code above, the line number reader, lrdr, forwards method calls to the file reader, frdr. Decorators add functionality either before or after forwarding to the object they decorate; for example, our line number reader tracks the current line number as it reads from an input stream.

Alternatively, of course, you could write Example 1 like this:

LineNumberReader lrdr = new LineNumberReader(new FileReader(filename));



Example 2. Using I/O decorators


try {
LineNumberReader lrdr = new LineNumberReader(new FileReader(filename));
for(String line; (line = lrdr.readLine()) != null;)rticle.txt {
System.out.print(lrdr.getLineNumber() + ":\t" + line);
}
}
catch(java.io.FileNotFoundException fnfx) {
fnfx.printStackTrace();
}
catch(java.io.IOException iox) {
iox.printStackTrace();
}


Decorators represent a powerful alternative to inheritance. Whereas inheritance lets you add functionality to classes at compile time, decorators let you add functionality to objects at runtime.

Decorator Pattern

The Decorator Pattern is used for adding additional functionality to a particular object as opposed to a class of objects. It is easy to add functionality to an entire class of objects by subclassing an object, but it is impossible to extend a single object this way. With the Decorator Pattern, you can add functionality to a single object and leave others like it unmodified.
A Decorator, also known as a Wrapper, is an object that has an interface identical to an object that it contains. Any calls that the decorator gets, it relays to the object that it contains, and adds its own functionality along the way, either before or after the call. This gives you a lot of flexibility, since you can change what the decorator does at runtime, as opposed to having the change be static and determined at compile time by subclassing. Since a Decorator complies with the interface that the object that it contains, the Decorator is indistinguishable from the object that it contains.  That is, a Decorator is a concrete instance of the abstract class, and thus is indistinguishable from any other concrete instance, including other decorators.   This can be used to great advantage, as you can recursively nest decorators without any other objects being able to tell the difference, allowing a near infinite amount of customization.

Decorators add the ability to dynamically alter the behavior of an object because a decorator can be added or removed from an object without the client realizing that anything changed.  It is a good idea to use a Decorator in a situation where you want to change the behaviour of an object repeatedly (by adding and subtracting functionality) during runtime.    
The dynamic behavior modification capability also means that decorators are useful for adapting objects to new situations without re-writing the original object's code.
The code for a decorator would something like this:
void doStuff() { 

// any pre-processing code goes here.
   aComponent.doStuff() // delegate to the decoree
// any post-processing code goes here
}



Note that the decorator can opt to not delegate to the decoree, if, for instance, some condition was not met.
A very nice example of decorators is Java's I/O stream implementation.
 

Example


Component


public abstract class Breakfast {

String description = "Unknown Breakfast";

public String getDescription() {
return description;
}
public abstract double cost();
}

Concrete Component

The ConcreteComponent is the object we’re going to dynamically add new behavior to. It extends Component.

public class Dosa extends Breakfast{

public Dosa() {
description = "Dosa";
}

public double cost(){
return 12.50;
}
}

 

Another Component:

 


public class Idli extends Breakfast{

public Idli() {
description = "Idli";
}
public double cost(){
return 10.50;
}
}

Decorator

Each decorator HAS-A (wraps) a component, which means the decorator has an instance variable that holds a reference to a component.
Decorators implement the same interface or abstract class as the component they are going to decorate.


// Decorator
public abstract class Decorator extends Breakfast{

public abstract String getDescription();

}


Concrete Decorator:
The ConcreteDecorator has an instance variable for the thing it decorates (the Component the Decorator wraps).

public class MasalaDosaDecorator extends Decorator{

Breakfast breakfast;

public MasalaDosaDecorator(Breakfast breakfast){
this.breakfast = breakfast;
}

public String getDescription(){
return breakfast.getDescription()+" ,its MasalaDosa";
}

public double cost(){
return breakfast.cost() + 5.50;
}
}


Now have another concrete decorator, say OnionDosaDecorator:



public class OnionDosaDecorator extends Decorator{

Breakfast breakfast;

public OnionDosaDecorator(Breakfast breakfast){
this.breakfast = breakfast;
}

public String getDescription(){
return breakfast.getDescription()+" , its OnionDosa";
}

public double cost(){
return breakfast.cost() + 3.50;
}
}


Decorator Demo : Time to order dosa.


Now its time to have our menu to be served, with main function.



public class BreakfastMenu {

public static void main(String[] args) {

// without adding decorators
Breakfast menu1 = new Dosa();
System.out.println(menu1.getDescription() +" Rs. "+menu1.cost());


//adding decorators
Breakfast menu2 = new MasalaDosaDecorator(new OnionDosaDecorator(new Dosa()));
System.out.println(menu2.getDescription() +" Rs. "+menu2.cost());

Breakfast menu3 = new MasalaDosaDecorator(new Dosa());
System.out.println(menu3.getDescription() +" Rs. "+menu3.cost());
}
}

Decorators can extend the state of the component.
Decorators can add new methods. however new behavior is typically added by doing computation before or after an existing method in the component.
Inheritance is one form of extension, but not necessarily the best way to achieve flexibility in our designs.
In our designs we should allow behavior to be extended without the need to modify existing code.
Composition and delegation can often be used to add new behaviors at runtime.
The Decorator Pattern provides an alternative to subclassing for extending behavior.
The Decorator Pattern involves a set of decorator classes that are used to wrap concrete components.
Decorator classes mirror the type of the components they decorate. (In fact, they are the same type as the components they decorate, either through inheritance or interface implementation.)
Decorators change the behavior of their components by adding new functionality before and/or after (or even in place of) method calls to the component.
You can wrap a component with any number of decorators.
Decorators are typically transparent to the client of the component; that is, unless the client is relying on the component’s concrete type.
Decorators can result in many small objects in our design, and overuse can be complex.
Adapter provides a different interface to its subject.Proxy provides the same interface.Decorator provides an enhanced interface.[GoF, p216]
Adapter changes the object's interface,Decorator enhances an object's responsibilities.Decorator is thus more transparent to the client.As a consequence,Decorator supports recursive composition,which isnt possible with pure Adapters.[GoF, p149]
Composite and Decorator have similar structure diagrams,reflecting the fact that both rely on recursive composition to organize an open-ended number of objects.[GoF, p219]
A Decorator can be viewed as a degenerate Composite with only one component.However a decorator adds additional responsibilities-it isnt intended for object aggregation.[GoF, p184]
Decorator is designed to let you add responsibilites to objects without subclassing.Composite's focus is not an embellishment but on representation.These intents are distinct but complementary.Consequently Composite and Decorator are often used in concert. [GoF, p220]
Decorator lets us change the skin of an object.Strategy lets us change the guts.[GoF, p184]
Decorator and Proxy have diff purposes but similar structures.Both describe how to provide a level of indirection to another object,and the implementations keep a reference to the object to which they forward requests.[GoF, p220]

Disadvantage



Only disadvantage is code maintenance can be a problem as it provides the system with a lot of similar looking small objects(each decorator).

Strategy pattern

The Strategy Design Pattern basically consists of decoupling an algorithm from its host, and encapsulating the algorithm into a separate class. More simply put, an object and its behaviour are separated and put into two different classes. This allows you to switch the algorithm that you are using at any time.

There are several advantages to doing this. First, if you have several different behaviours that you want an object to perform, it is much simpler to keep track of them if each behaviour is a separate class, and not buried in the body of some method. Should you ever want to add, remove, or change any of the behaviours, it is a much simpler task, since each one is its own class. Each such behaviour or algorithm encapsulated into its own class is called a Strategy.

When you have several objects that are basically the same, and differ only in their behaviour, it is a good idea to make use of the Strategy Pattern.. Using Strategies, you can reduce these several objects to one class that uses several Strategies. The use of strategies also provides a nice alternative to subclassing an object to achieve different behaviours. When you subclass an object to change its behaviour, that behaviour that it executes is static. If you wanted to change what it does, you'd have to create a new instance of a different subclass and replace that object with it. With Strategies, however, all you need to do is switch the object's strategy, and it will immediately change how it behaves. Using Strategies also eliminates the need for many conditional statements. When you have several behaviours together in one class, it is difficult to choose among them without resorting to conditional statements. If you use Strategies you won't need to check for anything, since whatever the current strategy is just executes without asking questions.

strategy_implementation_-_uml_class_diagram

So context has strategy reference and it changes it strategy whenever needed, by using it setters for that strategy reference.

Example

Strategy.java
Suppose we are into making cake, and there are few strategies of making cake.

package com.cakes;

public interface Strategy {

boolean checkTemperature(int temperatureInF);

}


Strategy1


The HikeStrategy class is a concrete strategy class that implements the Strategy interface. The checkTemperature method is implemented so that if the temperature is between 50 and 90, it returns true. Otherwise it returns false.

HikeStrategy.java

package com.cakes;

public class HikeStrategy implements Strategy {

@Override
public boolean checkTemperature(int temperatureInF) {
if ((temperatureInF >= 50) && (temperatureInF <= 90)) {
return true;
} else {
return false;
}
}

}



Strategy 2 :


The SkiStrategy implements the Strategy interface. If the temperature is 32 or less, the checkTemperature method returns true. Otherwise it returns false.

SkiStrategy.java

package com.cakes;

public class SkiStrategy implements Strategy {

@Override
public boolean checkTemperature(int temperatureInF) {
if (temperatureInF <= 32) {
return true;
} else {
return false;
}
}

}



Context


The Context class contains a temperature and a reference to a Strategy. The Strategy can be changed, resulting in different behavior that operates on the same data in the Context. The result of this can be obtained from the Context via the getResult() method.

package com.cakes;

public class Context {

int temperatureInF;
Strategy strategy;

public Context(int temperatureInF, Strategy strategy) {
this.temperatureInF = temperatureInF;
this.strategy = strategy;
}

public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}

public int getTemperatureInF() {
return temperatureInF;
}

public boolean getResult() {
return strategy.checkTemperature(temperatureInF);
}

}


Demo of pattern


The Demo class creates a Context object with a temperature of 60 and with a SkiStrategy. It displays the temperature from the context and whether that temperature is OK for skiing. After that, it sets the Strategy in the Context to HikeStrategy. It then displays the temperature from the context and whether that temperature is OK for hiking.


Demo.java

package com.cakes;

public class Demo {

public static void main(String[] args) {

int temperatureInF = 60;

Strategy skiStrategy = new SkiStrategy();
Context context = new Context(temperatureInF, skiStrategy);

System.out.println("Is the temperature (" + context.getTemperatureInF() + "F) good for skiing? " + context.getResult());

Strategy hikeStrategy = new HikeStrategy();
context.setStrategy(hikeStrategy);

System.out.println("Is the temperature (" + context.getTemperatureInF() + "F) good for hiking? " + context.getResult());

}

}



Console Output
Is the temperature (60F) good for skiing? false
Is the temperature (60F) good for hiking? true

Polyglot programming : Definition

In computing, a polyglot is a computer program or script written in a valid form of multiple programming languages, which performs the same operations or output independent of the programming language used to compile or interpret it.
Generally polyglots are written in a combination of C (which allows redefinition of tokens with a preprocessor) and a scripting language such as Lisp, Perl or sh.

So the application using polyglot have access to low level resources provided by lisp and also scripting gives it edge to use these resources in better way.

Saturday 26 February 2011

Observer and Observable pattern in Java

Definition
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
The Observer pattern allows one object (the observer) to watch another (the subject). The Observer pattern allows the subject and observer to form a publish-subscribe relationship. Through the Observer pattern, observers can register to receive events from the subject. When the subject needs to inform its observers of an event, it simply sends the event to each observer.
For example, you might have a spreadsheet that has an underlying data model. Whenever the data model changes, the spreadsheet will need to update the spreadsheet screen and an embedded graph. In this example, the subject is the data model and the observers are the screen and graph. When the observers receive notification that the model has changes, they can update themselves.
 
Lets have 2 interfaces:
public interface Subject {
public void addObserver( Observer o );
public void removeObserver( Observer o );
}
public interface Observer {
public void update( Subject o );
}

So concrete classes implementing these interface must have these methods. In the subject class, we will call update passing reference of the Observer class and call update accordingly.

So creating the subject….say it is an integer bag…which can be modified and it has to notify its observer when some events happen. IntegerDataBag which implements Subject holds onto Integer instances. The IntegerDataBag also allows Observers to add and remove themselves.
import java.util.ArrayList;
import java.util.Iterator;
public class IntegerDataBag implements Subject {
private ArrayList list = new ArrayList(); //list of observables, integer here
private ArrayList observers = new ArrayList();//list of observers
public void add( Integer i ) {
list.add( i ); //when adding int to int bag, notify all
notifyObservers();
}
public Iterator iterator() {
return list.iterator();
}
public Integer remove( int index ) {
if( index &lt; list.size() ) {
Integer i = (Integer) list.remove( index );
notifyObservers();//when removing int to int bag, notify all
return i;
}
return null;
}
public void addObserver( Observer o ) {
observers.add( o );
}
public void removeObserver( Observer o ) {
observers.remove( o );
}
private void notifyObservers() {
// loop through and notify each observer
Iterator i = observers.iterator();
while( i.hasNext() ) {
Observer o = ( Observer ) i.next();
o.update( this );//Calls update method of Observer as notification
}
}
}

Consider these two implementations of Observer -- IntegerAdder and IntegerPrinter:

Observer1
import java.util.Iterator;
public class IntegerAdder implements Observer {
private IntegerDataBag bag; //Observable or subject
public IntegerAdder( IntegerDataBag bag ) {
this.bag = bag;
bag.addObserver( this );//Observer1 adds itself to observable list
}
public void update( Subject o ) {
if( o == bag ) {
System.out.println( "The contents of the IntegerDataBag have changed." );
int counter = 0;
Iterator i = bag.iterator();
while( i.hasNext() ) {
Integer integer = ( Integer ) i.next();
counter+=integer.intValue();
}
System.out.println( "The new sum of the integers is: " + counter );
}
}
}

Observer2
import java.util.Iterator;
public class IntegerPrinter implements Observer {
private IntegerDataBag bag;
public IntegerPrinter( IntegerDataBag bag ) {
this.bag = bag;
bag.addObserver( this );//Observer1 adds itself to observable list
}
public void update( Subject o ) {
if( o == bag ) {
System.out.println( "The contents of the IntegerDataBag have changed." );
System.out.println( "The new contents of the IntegerDataBag contains:" );
Iterator i = bag.iterator();
while( i.hasNext() ) {
System.out.println( i.next() );
}
}
}
}

IntegerAdder and IntegerPrinter add themselves to the integer bag as observers. When an IntegerAdder receives an update, it sums up the Integer values held in the bag and displays them. Likewise, when IntegerPrinter receives an update, it prints out the Integers held in the bag.

Here is a simple main() that exercises these classes:
public class Driver {
public static void main( String [] args ) {
Integer i1 = new Integer( 1 ); Integer i2 = new Integer( 2 );
Integer i3 = new Integer( 3 ); Integer i4 = new Integer( 4 );
Integer i5 = new Integer( 5 ); Integer i6 = new Integer( 6 );
Integer i7 = new Integer( 7 ); Integer i8 = new Integer( 8 );
Integer i9 = new Integer( 9 );
IntegerDataBag bag = new IntegerDataBag();
bag.add( i1 ); bag.add( i2 ); bag.add( i3 ); bag.add( i4 );
bag.add( i5 ); bag.add( i6 ); bag.add( i7 ); bag.add( i8 );
IntegerAdder adder = new IntegerAdder( bag );
IntegerPrinter printer = new IntegerPrinter( bag );
// adder and printer add themselves to the bag
System.out.println( "About to add another integer to the bag:" );
bag.add( i9 );
System.out.println("");
System.out.println("About to remove an integer from the bag:");
bag.remove( 0 );
}
}
04-qa-0525-observer1

The IntegerDataBag/IntegerAdder/IntegerPrinter is a simple example of the Observer pattern. Within Java itself there are a number of examples of the Observer pattern: the AWT/Swing event model, as well as the java.util.Observer and java.util.Observable interfaces serve as examples.

So the picture goes like this:

One-to-many relationship
The subject and observers define the one-to-many relationship. The observers are dependent on the subject such that when the subject’s state changes, the observers get notified.  Depending on the style of notification, the observer may also be updated with new values. With the Observer pattern, the Subject is the object that contains the state and controls it. So, there is ONE subject with state. The observers, on the other hand, use the state, even if they don’t own it. There are many observers and they rely on the Subject to tell them when its state changes.
So there is a relationship between the ONE Subject to the MANY Observers.



Extending books to loanable and reference books

class LoanBook extends Book
{
public LoanBook (String t, String a, int c1, int c2, float p)
{
super(t,a,c1,c2,p);
}

public boolean canLoan()
{
return true;
}

public String details ()
{
return "Loan: "+super.details();
}

public String toString()
{
return "loan: "+super.toString();
}
}

class ReferenceBook extends Book
{
public ReferenceBook (String t, String a, int c1, int c2, float p)
{
super(t,a,c1,c2,p);
}

public boolean canLoan()
{
return false;
}

public String details ()
{
return "Reference: "+super.details();
}

public String toString()
{
return "Ref: "+super.toString();
}
}



class Loan
{
Book book;
Person person;
Date date = new Date();

public Loan (Book b, Person p)
{
book = b;
person = p;
}

public String details ()
{
return book.details()+" loaned on "+date+" to "+person.details();
}

public String toString()
{
return "book "+book+" -&gt; person"+person+" @date "+date;
}
}

public class Library
{
public static void main(String[] args)
{
Book b1 = new LoanBook ("Java I/O Programming","E.R.Harrold",123,45,18.99F);
Book b2 = new LoanBook ("Java in a Nutshell","D.Flanagan",123,25,12.99F);
Book b3 = new ReferenceBook ("The Java CLass Libraries","P.Chan &amp; R.Lee",2123,10,35.00F);

System.out.println("Books");
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
System.out.println("");

System.out.println("People:");
Person james = new Person ("James Gosling");
System.out.println(james);
System.out.println("");

Loan l1 = makeLoan(james, b1);
Loan l2 = makeLoan(james, b2);
Loan l3 = makeLoan(james, b3);
}

private static Loan makeLoan(Person p, Book b)
{
Loan l=null;
if (b.canLoan())
{
l = new Loan(b,p);
System.out.println(l.details());
}
else
System.out.println("Cannot loan "+b.details()+" to "+p.details());
System.out.println("");
return l;
}


}

Making library of books

To have library we can have 2 components for sure:
1. Books
2. Person borrowing that books

So we need a person class
class Person
{
String name;
public Person (String n)
{
name = n;
}

public String details ()
{
return name;
}

public String toString()
{
return "name &lt;"+name+"&gt;";
}
}
 
Person must take membership from library...so something has to be added to above
class Membership
{
public boolean canLoan(int onLoan)
{
return false;
}
}

class JuniorMember extends Membership
{
public boolean canLoan(int onLoan)
{
return onLoan&lt;1;
}
public String toString()
{
return "Junior";
}
}

class StandardMember extends Membership
{
public boolean canLoan(int onLoan)
{
return onLoan&lt;6;
}
public String toString()
{
return "Standard";
}
}

class OAPMember extends Membership
{
public boolean canLoan(int onLoan)
{
Calendar now = Calendar.getInstance();
int day = now.get(Calendar.DAY_OF_WEEK);
//if (day==Calendar.SATURDAY || day==Calendar.SUNDAY)
if (day == Calendar.THURSDAY)
return false;
return true;
}
public String toString()
{
return "OAP";
}
}
We have to add how many books person borrowed...so we have to add following function:
 So now person class become:
public class Person
{
String name;
Membership mem;
int books;
public Person (String n, Membership member)
{
name = n;
mem = member;
}

public boolean borrow(Book b)
{
if (b.canLoan() &amp;&amp; mem.canLoan(books))
{
books++;
return true;
}
return false;
}

public String details ()
{
return name+":"+mem;
}

public String toString()
{
return "name &lt;"+name+"&gt; "+mem;
}
}

General way of making class : Book

class Book
{
String title;
String author;
float price;
int cat, subCat;

public Book (String t, String a, int c1, int c2, float p)
{
title = t;
author = a;
price = p;
cat = c1;
subCat = c2;
}

public String details ()
{
return title+", "+author+" Category "+cat+"."+subCat+" value $"+price;
}

public String toString()
{
return "Title &lt;"+title+"&gt; Author &lt;"+author+"&gt; cat:"+cat+" subCat:"+subCat+" price:"+price;
}
}

Singleton pattern

Step 1: Provide a default Private constructor
public class Singleton {

// Note that the constructor is private
private Singleton() {
// Optional Code
}
}
Step 2: Create a Static Method for getting the reference to the Singleton Object
public class Singleton {

private static Singleton instance;
// Note that the constructor is private
private Singleton() {
// Optional Code
}
public static Singleton getInstance() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
}
We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.

Step 3: Make the Access method Synchronized to prevent Thread Problems.
public static synchronized Singleton getInstance()
It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below
SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();
This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.
class Singleton {

private static Singleton singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private Singleton() {
// Optional Code
}
public static synchronized Singleton getInstance() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}

public class SingletonObjectDemo {

public static void main(String args[]) {
// Singleton obj = new Singleton(); //Compilation error not allowed 
Singleton obj = Singleton.getInstance();
// Your Business Logic
System.out.println("Singleton object obtained");
}
}



Another approach
We don’t need to do a lazy initialization of the instance object or to check for null in the get method. We can also make the singleton class final to avoid sub classing that may cause other problems.
public class SingletonClass {

private static Singleton ourInstance = new Singleton();
public static SingletonClass getInstance() {
return singletonObj;
}
private SingletonClass() {
}
}
In Summary, the job of the Singleton class is to enforce the existence of a maximum of one object of the same type at any given time. Depending on your implementation, your class and all of its data might be garbage collected. Hence we must ensure that at any point there must be a live reference to the class when the application is running.

But still there are some issues left.
Protected vs Private Constructor 
protected Singleton() {
// ...
}
The constructor could be made private to prevent others from instantiating 
this class. But this would also make it impossible to create instances of 
Singleton subclasses.
 

Sunday 20 February 2011

Flyweight Pattern

Flyweight design pattern is a software design pattern used to minimize memory usage by sharing data. It enables use of large number of objects that would typically require a lot of memory.

A common example of the Flyweight pattern is string pooling. Consider the Java programming language. The String data type is immutable. Because it is guaranteed that the string can never be changed the strings are pooled to ensure that only one instance exists in memory at any given time.

So if you create two strings s1 and s2 which both point to "foo" you really have two pointers to the same location in memory.

Java also employs the Flyweight pattern for Integer object. new Integer(0) actually returns a pointer to pre-constructed object. So if you create one-thousand Objects which each contain an Object of type Integer you will only have one Integer(0) which is an excellent way to save memory.

Structure Summary
  1. Choose a class from which so many instances will be created that performance will suffer.
  2. Identify the state associated with the class that will not vary from one instance to another,and the state that is peculiar to each individual instance.
  3. State that is peculiar i.e cannot be shared will be maintained and supplied by client.
  4. Hundreds of objects can now be exercised by caching and reusing a few "flyweight" objects.
Types of states in FlyWeight object
Flyweight pattern describes how to share objects to allow their use at fine granularities without prohibitive cost.Each "Flyweight" object is divided into 2 pieces.
The state dependent(extrensic) part and the state-independent(intrinsic) part.

Intrinsic state is stored(shared) in the Flyweight object.
Extrensic state is stored or computed by client objects,and passed to the Flyweight when its operations are invoked.

Flyweights are shared objects and that using them can result in substantial performance gains.
Flyweights are typically instantiated by a flyweight factory that creates a limited number of flyweights and doles them out,one at a time to clients.

For example, you might have a pool of line objects that know how to draw lines. In that case, the flyweight factory could create one line object for each line color, such as one object for white lines and another for blue lines.
Those lines, which are flyweights, get reused whenever you draw white or blue lines.
If you have a drawing with 1,000 white lines and 6,000 blue lines, only two lines—instead of 7,000—are actually instantiated.

In java strings specified at compile-time are flyweights—strings that contain the same character sequence are shared. That sharing can greatly reduce memory footprints, and therefore, increase performance. Strings computed at runtime, are not flyweights by default; however, you can force the issue with the String.intern() which returns flyweights for strings computed at runtime.


While your writing your programs consider if you could use the Flyweight pattern to save memory. An example I used was for a Object that contained three Strings. This tuple uniquely identified a configuration of runs that were stored in the database. The Strings were loaded via JDBC so they didn't get the String pooling provided by Java. Instead I made the constructor to the class private and exposed a public static method called 'get'. This method took the three strings and created the object if not already existing and returned a pointer. This cut my memory usage drastically.

Implementation

flyweight-design-pattern-uml

This UML diagram shows that, Flyweights are typically instantiated by a flyweight factory that creates a limited number of flyweights and sends them out, one at a time to its clients.


Clients don’t instantiate flyweights directly; instead they get them from a Flyweight Factory. The factory first checks to see if it has a flyweight that fits specific criteria; if so, the factory returns a reference to the flyweight. If the factory can’t locate a flyweight for the specified criteria, it instantiates one, adds it to the pool, and returns it to the client.

Flyweight declares an interface through which flyweights can receive and act on extrinsic state. ConcreteFlyweight implements the Flyweight interface and adds storage for intrinsic state, if any in order to share an object. FlyweightFactory creates and manages flyweight objects. We can understand the flyweight pattern better using a simple example. Suppose, you want to show a file system with folders to show the directories or subdirectories, then you don’t need to load all the files or directories at one loading time. You may show the upper level folders first. If the user clicks a folder, then load its subdirectories and files. The shared trigger is mouse-clicked. The composite pattern may be combined to define the flyweight system.

Example
Here is an example of my use of the Flyweight pattern.
IFlyWeight.java -  the interface

interface IFlyWeight {
public String getName();
public String getAddress();
}

The IFlyWeight is an interface thatreturns the name and address of theemployees based on their specific criteria“division”.

FlyweightClient.java
public class FlyweightClient {
public static void main(String[] args)
throws Exception {
Vector empList = store();
FlyweightFactory factory =
FlyweightFactory.getInstance();
for (int i = 0; i < empList.size(); i++) {
StringTokenizer st = new StringTokenizer();
String division = st.nextToken();
IFlyWeight flyweight =
factory.getFlyweight(division);
// associate the flyweight
// with the extrinsic data object.
VCard card = new VCard(name, flyweight);
card.print();
}
}
private static Vector store() {
Vector v = new Vector();
v.add(“North”);
v.add(“South”);
v.add(“North”);
return v;
}
}

FlyweightFactory.java
class FlyweightFactory {
private HashMap lstFlyweight;
private static FlyweightFactory factory = new
FlyweightFactory();
private FlyweightFactory() {
lstFlyweight = new HashMap();
}
public synchronized IFlyweight getFlyweight(String divisionName) {
if (lstFlyweight.get(divisionName) == null) {
IFlyWeight fw = new
Flyweight(divisionName);
lstFlyweight.put(divisionName, fw);
return fw;
} else {
return
(IFlyWeight)lstFlyweight.get(divisionName);
}
}
public static FlyweightFactory getInstance() {
return factory;
}
Note that FlyWeightFactory class is not yet complete, as we have to add private class called FlyWeight class to it.
The client accesses this factory of employees. Every time, the client wants the information, which is accessed through this Factory class. The specifications are passed through the method parameters and new employee information is returned.

Flyweight class(continued in FlyWeightFactory)
//Inner flyweight class
private class Flyweight
implements IFlyweight {
private String name;
private String addr;
private void setValues(String name, String addr) {
this.name = name;
this.addr = addr;
}
private Flyweight(String division) {
if (division.equals(“North”)) {
setValues(“soniya”, “addr1”);
}
if (division.equals(“South”)) {
setValues(“rahul”, “addr2”);
}
if (division.equals(“East”)) {
setValues(“Aqil”, “addr3”);
}
}
public String getName() {
return company;
}
public String getAddress() {
return address;
}
}// end of Flyweight
}// end of FlyweightFactory
class VCard {
String name;
String title;
IFlyweight objFW;
public VCard(String n, IFlyWeight fw) {
name = n;
objFW = fw;
}
public void print() {
System.out.println(name);
System.out.println(name objFW.getAddress());
}
}



When to use Flightweight Pattern?
  • Use the Flightweight Pattern when one instance of a class can be used to provide many virtual instances.
  • Flightweight Pattern is used when a class has many instances, and they all can be controlled identically.
  • Application uses a large number of objects.
  • Storage(Memory) Cost is high to replicate this large number of multiple users.
  • Either the objects are immutable or their state can be made external.
  • Relatively few shared objects may replace many groups of objects.
  • Application does not depend on object identity.While the user may think they are getting a unique object, they actually have a reference from the cache.

The flyweight design pattern is not recommended when the objects in the cache change rapidly or unexpectedly.
Benifits of Flightweight Pattern
1. Reduces the number of object instances at runtime saving memory.
2. Centralizes state for many virtual objects into a single location.

Drawbacks of Flightweight Pattern
1. Drawback is that once you implemented it, single logical instances of the class will not be able to behave independently from the other instances.

Related Patterns
Abstract Factory,Singleton and Template Method patterns fall under this category.Flyweight pattern is often combined with the Composite Pattern to implement a logically hierarchical structure in terms of a directed-acyclic graph with shared lead nodes.Flyweight is a strategy in which you keep a pool of objects available and create references into the pool of objects for particular views.It uses the idea of canonical objects.A canonical object is a single representative object that represents all other objects for particular type.
Whereas flyweight shows how to make lots of little objects,Facade shows how to make a single object represent an entire subsystem.[GoF,p138]
Flyweight is often combined with Composite to implement shared leaf nodes.[GoF,p206]
Terminal symbols within Interpreter's abstract syntax tree can be shared with Flyweight. [GoF. p255]
Flyweights explain when and how State objects can be shared.[GoF,p313]

Checklist while implementing FlyWeight
  • Ensure the object overhead is an issue needing attention,and the client of the class is able and willing to absorb responsibility realignment.
  • Divide the target class's state into: shareable(intrinsic) state,and non-shareable(extrensic) state.
  • Remove the non-shareable state from the class attributes,and add it to the calling argument list of affected methods.
  • Create a factory that can cache and reuse existing class instances.
  • The client must use the Factory instead of the new operator to request objects.
  • The client(or a third party) must look-up or compute the non-shareable state,and supply that state to class methods.

Summary
Flyweight pattern is kind of optimization, but adds to the complexity of the code, so it must be checked whether after adding flyweight performance really improved. Remember the quote from Donald Knuth: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil ."Also even java is not providing caching for objects like String, until and unless you use intern() method, because object creation is becoming cheaper and cheaper. So think of it when you really have very very large no. of objects.

Wednesday 16 February 2011

Forwarding

In case of composition, each instance method in the new class which contains or is composed of other class, invokes the corresponding method on the contained instance of the existing class and returns the results. This is known as forwarding, and the methods in the new class are known as forwarding methods.

Tuesday 1 February 2011

Composition vs Inheritance 2

Dynamic binding, polymorphism, and change
When you establish an inheritance relationship between two classes, you get to take advantage of dynamic binding and polymorphism. Dynamic binding means the JVM will decide at runtime which method implementation to invoke based on the class of the object. Polymorphism means you can use a variable of a superclass type to hold a reference to an object whose class is the superclass or any of its subclasses.
One of the prime benefits of dynamic binding and polymorphism is that they can help make code easier to change. If you have a fragment of code that uses a variable of a superclass type, such as Fruit, you could later create a brand new subclass, such as Banana, and the old code fragment will work without change with instances of the new subclass. If Banana overrides any of Fruit's methods that are invoked by the code fragment, dynamic binding will ensure that Banana's implementation of those methods gets executed. This will be true even though class Banana didn't exist when the code fragment was written and compiled.
Thus, inheritance helps make code easier to change if the needed change involves adding a new subclass. This, however, is not the only kind of change you may need to make.
Changing the superclass interface
In an inheritance relationship, superclasses are often said to be "fragile," because one little change to a superclass can ripple out and require changes in many other places in the application's code. To be more specific, what is actually fragile about a superclass is its interface. If the superclass is well-designed, with a clean separation of interface and implementation in the object-oriented style, any changes to the superclass's implementation shouldn't ripple at all. Changes to the superclass's interface, however, can ripple out and break any code that uses the superclass or any of its subclasses. What's more, a change in the superclass interface can break the code that defines any of its subclasses.
For example, if you change the return type of a public method in class Fruit (a part of Fruit's interface), you can break the code that invokes that method on any reference of type Fruit or any subclass of Fruit. In addition, you break the code that defines any subclass of Fruit that overrides the method. Such subclasses won't compile until you go and change the return value of the overridden method to match the changed method in superclass Fruit.
Inheritance is also sometimes said to provide "weak encapsulation," because if you have code that directly uses a subclass, such as Apple, that code can be broken by changes to a superclass, such as Fruit. One of the ways to look at inheritance is that it allows subclass code to reuse superclass code. For example, if Apple doesn't override a method defined in its superclass Fruit, Apple is in a sense reusing Fruit's implementation of the method. But Apple only "weakly encapsulates" the Fruit code it is reusing, because changes to Fruit's interface can break code that directly uses Apple.

Composition vs Inheritance

The composition alternative
Given that the inheritance relationship makes it hard to change the interface of a superclass, it is worth looking at an alternative approach provided by composition. It turns out that when your goal is code reuse, composition provides an approach that yields easier-to-change code.
Code reuse via inheritance
For an illustration of how inheritance compares to composition in the code reuse department, consider this very simple example:

class Fruit {

// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {

System.out.println("Peeling is appealing.");
return 1;
}
}

class Apple extends Fruit {
}

class Example1 {

public static void main(String[] args) {

Apple apple = new Apple();
int pieces = apple.peel();
}
}
When you run the Example1 application, it will print out "Peeling is appealing.", because Apple inherits (reuses) Fruit's implementation of peel(). If at some point in the future, however, you wish to change the return value of peel() to type Peel, you will break the code for Example1. Your change to Fruit breaks Example1's code even though Example1 uses Apple directly and never explicitly mentions Fruit.
Here's what that would look like:

class Peel {

private int peelCount;

public Peel(int peelCount) {
this.peelCount = peelCount;
}

public int getPeelCount() {

return peelCount;
}
//...
}

class Fruit {

// Return a Peel object that
// results from the peeling activity.
public Peel peel() {

System.out.println("Peeling is appealing.");
return new Peel(1);
}
}

// Apple still compiles and works fine
class Apple extends Fruit {
}

// This old implementation of Example1
// is broken and won't compile.
class Example1 {

public static void main(String[] args) {

Apple apple = new Apple();
int pieces = apple.peel();
}
}
Code reuse via composition
Composition provides an alternative way for Apple to reuse Fruit's implementation of peel(). Instead of extending Fruit, Apple can hold a reference to a Fruit instance and define its own peel() method that simply invokes peel() on the Fruit. Here's the code:

class Fruit {

// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {

System.out.println("Peeling is appealing.");
return 1;
}
}

class Apple {

private Fruit fruit = new Fruit();

public int peel() {
return fruit.peel();
}
}

class Example2 {

public static void main(String[] args) {

Apple apple = new Apple();
int pieces = apple.peel();
}
}
In the composition approach, the subclass becomes the "front-end class," and the superclass becomes the "back-end class." With inheritance, a subclass automatically inherits an implemenation of any non-private superclass method that it doesn't override. With composition, by contrast, the front-end class must explicitly invoke a corresponding method in the back-end class from its own implementation of the method. This explicit call is sometimes called "forwarding" or "delegating" the method invocation to the back-end object.
The composition approach to code reuse provides stronger encapsulation than inheritance, because a change to a back-end class needn't break any code that relies only on the front-end class. For example, changing the return type of Fruit's peel() method from the previous example doesn't force a change in Apple's interface and therefore needn't break Example2's code.
Here's how the changed code would look:

class Peel {

private int peelCount;

public Peel(int peelCount) {
this.peelCount = peelCount;
}

public int getPeelCount() {

return peelCount;
}
//...
}

class Fruit {

// Return int number of pieces of peel that
// resulted from the peeling activity.
public Peel peel() {

System.out.println("Peeling is appealing.");
return new Peel(1);
}
}

// Apple must be changed to accomodate
// the change to Fruit
class Apple {

private Fruit fruit = new Fruit();

public int peel() {

Peel peel = fruit.peel();
return peel.getPeelCount();
}
}

// This old implementation of Example2
// still works fine.
class Example1 {

public static void main(String[] args) {

Apple apple = new Apple();
int pieces = apple.peel();
}
}
This example illustrates that the ripple effect caused by changing a back-end class stops (or at least can stop) at the front-end class. Although Apple's peel() method had to be updated to accommodate the change to Fruit, Example2 required no changes.

Comparing composition and inheritance 4


So how exactly do composition and inheritance compare? Here are several points of comparison:

  • It is easier to change the interface of a back-end class (composition) than a superclass (inheritance). As the previous example illustrated, a change to the interface of a back-end class necessitates a change to the front-end class implementation, but not necessarily the front-end interface. Code that depends only on the front-end interface still works, so long as the front-end interface remains the same. By contrast, a change to a superclass's interface can not only ripple down the inheritance hierarchy to subclasses, but can also ripple out to code that uses just the subclass's interface.
  • It is easier to change the interface of a front-end class (composition) than a subclass (inheritance). Just as superclasses can be fragile, subclasses can be rigid. You can't just change a subclass's interface without making sure the subclass's new interface is compatible with that of its supertypes. For example, you can't add to a subclass a method with the same signature but a different return type as a method inherited from a superclass. Composition, on the other hand, allows you to change the interface of a front-end class without affecting back-end classes.
  • Composition allows you to delay the creation of back-end objects until (and unless) they are needed, as well as changing the back-end objects dynamically throughout the lifetime of the front-end object. With inheritance, you get the image of the superclass in your subclass object image as soon as the subclass is created, and it remains part of the subclass object throughout the lifetime of the subclass.
  • It is easier to add new subclasses (inheritance) than it is to add new front-end classes (composition), because inheritance comes with polymorphism. If you have a bit of code that relies only on a superclass interface, that code can work with a new subclass without change. This is not true of composition, unless you use composition with interfaces. Used together, composition and interfaces make a very powerful design tool. I'll talk about this approach in next month's Design Techniques article.
  • The explicit method-invocation forwarding (or delegation) approach of composition will often have a performance cost as compared to inheritance's single invocation of an inherited superclass method implementation. I say "often" here because the performance really depends on many factors, including how the JVM optimizes the program as it executes it.
  • With both composition and inheritance, changing the implementation (not the interface) of any class is easy. The ripple effect of implementation changes remain inside the same class.