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.

Inheritance vs Composition

Choosing between composition and inheritance
So how do all these comparisons between composition and inheritance help you in your designs? Here are a few guidelines that reflect how I tend to select between composition and inheritance.
Make sure inheritance models the is-a relationship
My main guiding philosophy is that inheritance should be used only when a subclass is-a superclass. In the example above, an Apple likely is-a Fruit, so I would be inclined to use inheritance.
An important question to ask yourself when you think you have an is-a relationship is whether that is-a relationship will be constant throughout the lifetime of the application and, with luck, the lifecycle of the code. For example, you might think that an Employee is-a Person, when really Employee represents a role that a Person plays part of the time. What if the person becomes unemployed? What if the person is both an Employee and a Supervisor? Such impermanent is-a relationships should usually be modelled with composition.
Don't use inheritance just to get code reuse
If all you really want is to reuse code and there is no is-a relationship in sight, use composition.
Don't use inheritance just to get at polymorphism
If all you really want is polymorphism, but there is no natural is-a relationship, use composition with interfaces.

Wednesday, 12 January 2011

Factory pattern example in java

If you want to read about factory pattern, please refer this link - Factory Pattern.

Consider the following Button class, which has a single draw() method. Since this class is a generic class, we have made it as abstract.
Button.java

package tips.pattern.factory;

public abstract class Button {

public abstract void draw();

}

Given below are the concrete implementations of the Button class, WindowsButton and LinuxButton, each providing a much simplified implementation for the draw() method.
WindowsButton.java

package tips.pattern.factory;

public class WindowsButton extends Button{

@Override
public void draw() {
System.out.println("Drawing Windows Button");
}

}
LinuxButton.java

package tips.pattern.factory;

public class LinuxButton extends Button{

@Override
public void draw() {
System.out.println("Drawing Linux Button");
}

}

Now let us come to the core implementation, the Factory class itself. The ButtonFactory class has one static method called createButton() which the clients can invoke to get the Button object. Note the return type of the method, it is neither WindowsButton nor LinuxButton, but the super type of the both, i.e, Button. Whether the return type of method is WindowsButton or LinuxButton is decided based on the input operating system.
ButtonFactory.java

package tips.pattern.factory;

public class ButtonFactory {

public static Button createButton(String os){
if (os.equals("Windows")){
return new WindowsButton();
}else if (os.equals("Linux")){
return new LinuxButton();
}
return null;
}
}

Given below is the client Application that makes use of the above ButtonFactory class. The client is un-aware of the fact there is multiple implementations of the Button class. It accesses the draw() operation through a single unified type Button.
FactoryClient.java

package tips.pattern.factory;

public class FactoryClient {

public static void main(String[] args) {
Button windowsButton =
ButtonFactory.createButton("Windows");
windowsButton.draw();

Button linuxButton =
ButtonFactory.createButton("Linux");
linuxButton.draw();
}
}

So it is clear, that factory class fetches the client the corresponding class depending on the information provided by the client.