Saturday 12 March 2011

Use template for transactions

Code related to transactions is bulky, and has significant logic attached to it. Such code should not be repeated every time a transaction is required. Instead, define a template method which handles most of the processing of the transaction.
Example
Tx is a generic interface which can be applied to both
  • local transactions - attached to a single JDBC connection
  • distributed transactions (UserTransaction) - not attached to a single connection, or even to a single database

package hirondelle.web4j.database;

/**
Execute a database transaction.

<P>Should be applied only to operations involving more than one SQL statement.
*/

public interface Tx {

/**
Execute a database transaction, and return the number of edited records.
*/

int executeTx() throws DAOException;

}



TxTemplate is an implementation of Tx for local transactions. (An implementation for distributed transactions would be similar). It is an Abstract Base Class, and uses the template method design pattern. To implement a transaction, callers subclass TxTemplate, and provide a concrete implementation of executeMultipleSqls(Connection).
import java.sql.*;
import java.util.logging.*;

import hirondelle.web4j.BuildImpl;
import hirondelle.web4j.util.Util;
import hirondelle.web4j.util.Consts;

/**
* Template for executing a local, non-distributed transaction versus a single database,
* using a single connection.
*
* <P>This abstract base class implements the template method design pattern.
*/

public abstract class TxTemplate implements Tx {

//..elided

/**
* <b>Template</b> method calls the abstract method {@link #executeMultipleSqls}.
* <P>Returns the same value as <tt>executeMultipleSqls</tt>.
*
* <P>A <tt>rollback</tt> is performed if <tt>executeMultipleSqls</tt> throws
* a {@link SQLException} or
* {@link DAOException}, or if {@link #executeMultipleSqls(Connection)} returns
* {@link #BUSINESS_RULE_FAILURE}.
*/

public final int executeTx() throws DAOException {
int result = 0;
fLogger.fine(
"Editing within a local transaction, with isolation level : " + fTxIsolationLevel
);
ConnectionSource connSource = BuildImpl.forConnectionSource();
if(Util.textHasContent(fDatabaseName)){
fConnection = connSource.getConnection(fDatabaseName);
}
else {
fConnection = connSource.getConnection();
}

try {
TxIsolationLevel.set(fTxIsolationLevel, fConnection);
startTx();
result = executeMultipleSqls(fConnection);
endTx(result);
}
catch(SQLException rootCause){
fLogger.fine("Transaction throws SQLException.");
rollbackTx();
String message =
"Cannot execute edit. ErrorId code : " + rootCause.getErrorCode() +
Consts.SPACE + rootCause
;
if (rootCause.getErrorCode() == DbConfig.getErrorCodeForDuplicateKey().intValue()){
throw new DuplicateException(message, rootCause);
}
throw new DAOException(message, rootCause);
}
catch (DAOException ex){
fLogger.fine("Transaction throws DAOException.");
rollbackTx();
throw ex;
}
finally {
DbUtil.logWarnings(fConnection);
DbUtil.close(fConnection);
}
fLogger.fine("Total number of edited records: " + result);
return result;
}

/**
* Execute multiple SQL operations in a single local transaction.
*
* <P>This method returns the number of records edited. If a business rule
* determines that a
* rollback should be performed, then it is recommended that the special value
* {@link #BUSINESS_RULE_FAILURE} be returned by the implementation. This will
* signal to
* {@link #executeTx()} that a rollback must be performed. (Another option for
* signalling that a rollback is desired is to throw a checked exception.)
*
* <P><em>Design Note</em>: allowing <tt>SQLException</tt> in the <tt>throws</tt>
* clause simplifies the implementor significantly, since no <tt>try-catch</tt>
* blocks are needed. Thus, the caller has simple, "straight-line" code.
*
* @param aConnection must be used by all SQL statements participating in this
* transaction
* @return number of records edited by this operation. Implementations may return
* {@link #BUSINESS_RULE_FAILURE} if there is a business rule failure.
*/

public abstract int executeMultipleSqls(
Connection aConnection
) throws SQLException, DAOException;

/**
* Value {@value}. Special value returned by
* {@link #executeMultipleSqls(Connection)} to indicate that
* a business rule has been violated. Such a return value indicates to this class
* that a rollback must be performed.
*/

public static final int BUSINESS_RULE_FAILURE = -1;

// PRIVATE //

/**
* The connection through which all SQL statements attached to this
* transaction are executed. This connection may be for the default
* database, or any other defined database. See {@link #fDatabaseName}.
*/

private Connection fConnection;

/**
* Identifier for a non-default database. The connection taken from the default
* database only if this item has no content.
*/

private String fDatabaseName;

/**
* The transaction isolation level, defaults to level configured in
* <tt>web.xml</tt>.
*/

private final TxIsolationLevel fTxIsolationLevel;

private static final boolean fOFF = false;
private static final boolean fON = true;

private static final Logger fLogger = Util.getLogger(TxTemplate.class);

private void startTx() throws SQLException {
fConnection.setAutoCommit(fOFF);
}

private void endTx(int aNumEdits) throws SQLException, DAOException {
if ( BUSINESS_RULE_FAILURE == aNumEdits ) {
fLogger.severe("Business rule failure occured. Cannot commit transaction.");
rollbackTx();
}
else {
fLogger.fine("Commiting transaction.");
fConnection.commit();
fConnection.setAutoCommit(fON);
}
}

private void rollbackTx() throws DAOException {
fLogger.severe("ROLLING BACK TRANSACTION.");
try {
fConnection.rollback();
}
catch(SQLException ex){
throw new DAOException("Cannot rollback transaction", ex);
}
}
}



Here is a concrete implementation named RoleDAO. It has a change method which updates the roles attached to a user. The roles are stored in a cross-reference table. In this case, an update is implemented as 'delete all old, then add all new'. Note the lack of try..catch blocks in this class.
final class RoleDAO {

//..elided

/**
* Update all roles attached to a user.
*
* <P>This implementation will treat all edits to user roles as
* '<tt>DELETE-ALL</tt>, then <tt>ADD-ALL</tt>' operations.
*/

boolean change(UserRole aUserRole) throws DAOException {
Tx update = new UpdateTransaction(aUserRole);
return Util.isSuccess(update.executeTx());
}

// PRIVATE //

/** Cannot be a {@link hirondelle.web4j.database.TxSimple}, since there is looping. */
private static final class UpdateTransaction extends TxTemplate {
UpdateTransaction(UserRole aUserRole){
super(ConnectionSrc.ACCESS_CONTROL);
fUserRole = aUserRole;
}
public int executeMultipleSqls(
Connection aConnection
) throws SQLException, DAOException {
int result = 0;
//perform edits using a shared connection
result = result + DbTx.edit(aConnection, ROLES_DELETE, fUserRole.getUserName());
for(Id roleId : fUserRole.getRoles()){
result = result + DbTx.edit(aConnection,ROLES_ADD,fUserRole.getUserName(),roleId);
}
return result;
}
private UserRole fUserRole;
}
}


Template method for database operations

Template methods :
  • are used in most abstract base classes
  • are perhaps the most commonly used of all design patterns
  • define the general steps of a method, while deferring the implementation of at least one of the steps to a concrete subclass
ExampleTxTemplate is an abstract base class which defines a template method for executing multiple database operations within a transaction. It is useful to define these steps in one place. The alternative is to repeat the same structure every time a transaction is required. As usual, such code repetition should always be aggressively eliminated.
The executeTx method is the template method. It is final, and defines the general outline of how to execute a database transaction. The specific database actions to be taken are implemented by calling the abstract method executeMultipleSqls.
import java.sql.*;
import java.util.logging.*;

import hirondelle.web4j.BuildImpl;
import hirondelle.web4j.util.Util;
import hirondelle.web4j.util.Consts;

/**
* Template for executing a local, non-distributed transaction versus a single database,
* using a single connection.
*
* <P>This abstract base class implements the template method design pattern.
*/

public abstract class TxTemplate implements Tx {

//..elided

/**
* <b>Template</b> method calls the abstract method {@link #executeMultipleSqls}.
* <P>Returns the same value as <tt>executeMultipleSqls</tt>.
*
* <P>A <tt>rollback</tt> is performed if <tt>executeMultipleSqls</tt> throws
* a {@link SQLException} or
* {@link DAOException}, or if {@link #executeMultipleSqls(Connection)} returns
* {@link #BUSINESS_RULE_FAILURE}.
*/

public final int executeTx() throws DAOException {
int result = 0;
fLogger.fine(
"Editing within a local transaction, with isolation level : " + fTxIsolationLevel
);
ConnectionSource connSource = BuildImpl.forConnectionSource();
if(Util.textHasContent(fDatabaseName)){
fConnection = connSource.getConnection(fDatabaseName);
}
else {
fConnection = connSource.getConnection();
}

try {
TxIsolationLevel.set(fTxIsolationLevel, fConnection);
startTx();
result = executeMultipleSqls(fConnection);
endTx(result);
}
catch(SQLException rootCause){
fLogger.fine("Transaction throws SQLException.");
rollbackTx();
String message =
"Cannot execute edit. ErrorId code : " + rootCause.getErrorCode() +
Consts.SPACE + rootCause
;
if (rootCause.getErrorCode() == DbConfig.getErrorCodeForDuplicateKey().intValue()){
throw new DuplicateException(message, rootCause);
}
throw new DAOException(message, rootCause);
}
catch (DAOException ex){
fLogger.fine("Transaction throws DAOException.");
rollbackTx();
throw ex;
}
finally {
DbUtil.logWarnings(fConnection);
DbUtil.close(fConnection);
}
fLogger.fine("Total number of edited records: " + result);
return result;
}

/**
* Execute multiple SQL operations in a single local transaction.
*
* <P>This method returns the number of records edited. If a business rule
* determines that a
* rollback should be performed, then it is recommended that the special value
* {@link #BUSINESS_RULE_FAILURE} be returned by the implementation. This will
* signal to
* {@link #executeTx()} that a rollback must be performed. (Another option for
* signalling that a rollback is desired is to throw a checked exception.)
*
* <P><em>Design Note</em>: allowing <tt>SQLException</tt> in the <tt>throws</tt>
* clause simplifies the implementor significantly, since no <tt>try-catch</tt>
* blocks are needed. Thus, the caller has simple, "straight-line" code.
*
* @param aConnection must be used by all SQL statements participating in this
* transaction
* @return number of records edited by this operation. Implementations may return
* {@link #BUSINESS_RULE_FAILURE} if there is a business rule failure.
*/

public abstract int executeMultipleSqls(
Connection aConnection
) throws SQLException, DAOException;

/**
* Value {@value}. Special value returned by
* {@link #executeMultipleSqls(Connection)} to indicate that
* a business rule has been violated. Such a return value indicates to this class
* that a rollback must be performed.
*/

public static final int BUSINESS_RULE_FAILURE = -1;

// PRIVATE //

/**
* The connection through which all SQL statements attached to this
* transaction are executed. This connection may be for the default
* database, or any other defined database. See {@link #fDatabaseName}.
*/

private Connection fConnection;

/**
* Identifier for a non-default database. The connection taken from the default
* database only if this item has no content.
*/

private String fDatabaseName;

/**
* The transaction isolation level, defaults to level configured in
* <tt>web.xml</tt>.
*/

private final TxIsolationLevel fTxIsolationLevel;

private static final boolean fOFF = false;
private static final boolean fON = true;

private static final Logger fLogger = Util.getLogger(TxTemplate.class);

private void startTx() throws SQLException {
fConnection.setAutoCommit(fOFF);
}

private void endTx(int aNumEdits) throws SQLException, DAOException {
if ( BUSINESS_RULE_FAILURE == aNumEdits ) {
fLogger.severe("Business rule failure occured. Cannot commit transaction.");
rollbackTx();
}
else {
fLogger.fine("Commiting transaction.");
fConnection.commit();
fConnection.setAutoCommit(fON);
}
}

private void rollbackTx() throws DAOException {
fLogger.severe("ROLLING BACK TRANSACTION.");
try {
fConnection.rollback();
}
catch(SQLException ex){
throw new DAOException("Cannot rollback transaction", ex);
}
}
}



Here is an example of using TxTemplate. It alters the set of roles attached to an end user, first by deleting all existing roles, and then by adding the new roles one at a time.
final class RoleDAO {

//..elided

/**
* Update all roles attached to a user.
*
* <P>This implementation will treat all edits to user roles as
* '<tt>DELETE-ALL</tt>, then <tt>ADD-ALL</tt>' operations.
*/

boolean change(UserRole aUserRole) throws DAOException {
Tx update = new UpdateTransaction(aUserRole);
return Util.isSuccess(update.executeTx());
}

// PRIVATE //

/** Cannot be a {@link hirondelle.web4j.database.TxSimple}, since there is looping. */
private static final class UpdateTransaction extends TxTemplate {
UpdateTransaction(UserRole aUserRole){
super(ConnectionSrc.ACCESS_CONTROL);
fUserRole = aUserRole;
}
public int executeMultipleSqls(
Connection aConnection
) throws SQLException, DAOException {
int result = 0;
//perform edits using a shared connection
result = result + DbTx.edit(aConnection, ROLES_DELETE, fUserRole.getUserName());
for(Id roleId : fUserRole.getRoles()){
result = result + DbTx.edit(aConnection,ROLES_ADD,fUserRole.getUserName(),roleId);
}
return result;
}
private UserRole fUserRole;
}
}


Friday 11 March 2011

Minimize ripple effects

Much of object programming is centered on minimizing the ripple effects caused by changes to a program. This is done simply by keeping details secret (information hiding or encapsulation).

The principal ways of doing this are

  • indirection - named constants replacing "magic numbers", for example
  • minimizing visibility - private fields, package-private classes, for example
  • generic references (polymorphism) - using high level references (interfaces or abstract classes) instead of low level references (concrete classes)
All of these techniques accomplish the same thing - they confine knowledge of implementation details to the smallest possible part of a program. That is, they keep a secret of some sort.

Constant and liberal use of the above techniques is recommended.

An interesting quote from chapter one of Design Patterns, regarding the use of generic references :

"This so greatly reduces implementation dependencies between subsystems that it leads to the following principle of reusable object-oriented design :

Program to an interface, not an implementation.

Don't declare variables to be instances of particular concrete classes. Instead, commit only to an interface defined by an abstract class. You will find this to be a common theme of the design patterns in this book."

(They state a second principle as well: "Favor object composition over class inheritance.")

Avoid null if possible

Some argue that allowing null into the API of a class, in the form of possibly-null parameters or return values, should be avoided if possible :

  • null references can only be used in a boolean test - any other use will throw a NullPointerException
  • null references always represent special cases, and if these special cases can be removed, the code will be easier to understand
  • null return values are error prone, since there is no way to ensure that the caller always does a check-for-null.
  • methods which accept an explicit null reference as a valid argument are less intelligible at the point of call. The reader will usually need to consult documentation to determine what exactly the null argument means.

If null is allowed for a method, then this should be clearly stated in its javadoc. Some follow the convention that all items are assumed to be non-null unless otherwise specified. Such a convention could be explicitly stated once in the javadocoverview.html.

See also use zero sized arrays rather than null

Saturday 5 March 2011

Types of Design pattern

One way of classification of design pattern is :
Creational patterns: create objects for you, rather than your having to instantiate objects directly. Your program gains more flexibility in deciding which objects need to be created for a given case.Click here for creational patterns.
Structural patterns: help you compose groups of objects into larger structures, such as complex user interfaces and accounting data.Click here for structural pattern.
Behavioral patterns: help you to define the communication between objects in your system and how the flow is controlled in a complex program. Click here for behavioral pattern.

Wednesday 2 March 2011

Proxy Pattern

Proxy Pattern provides a surrogate or placeholder for another object to control the access. There are number of ways it can manage the access.
It means we are representing a complex object with a simpler one.

Motivation
The Need:
  • Control access to an object
  • Examples:
    • The object may be expensive to use (e.g., the manipulation of an image) and it may not be necessary to do so (e.g., because the image is not visible or because you are using a thumbnail)
    • The object being accessed may reside on a "remote"  address space/machine  and special "communications" may be required
    • The object being accessed may be "priveleged" (e.g., for security reasons) in some applications and not in others
Structure
Proxy Pattern

Proxy pattern category
-> A RemoteProxy manages interaction between a client and a remote object.
-> A Virtual Proxy controls access to an object that is expensive to instantiate.
-> A Protection Proxy controls access to the methods of an object based on the caller.
-> A smart proxy interposes additional actions when an object is accessed. Typical uses include:
1. Counting the number of references to the real object so that it can be freed automatically when there are no more references
2. Loading a persistent object into memory when it's first referenced
3. Checking that the real object is locked before it is accessed to ensure that no other object can change it.
Even many other variants of Proxy Pattern exists.
When to use:
1. Use the proxy Pattern in situations where client does not or can not reference an
object directly, but wants to still interact with the object
2. Use the proxy Pattern to create a representative object that controls access to another object, which may be remote, expensive to create or in need of securing.
-> The proxy object has the same interface as the target object
-> The proxy holds a reference to the target object and can forward requests to
the target as required (delegation!)
-> In effect, the proxy object has the authority the act on behalf of the client to
interact with the target object
To make clients use Proxy rather than the Real One, provide a factory that instantiates and returns the subject. Because this happens in a factory method we can then wrap the real one with a proxy before returning it. The client never knows or cares that it's using a proxy instead of the real thing.
Let us take a real time use of Proxy Pattern as an example.
By the way this code bit is from my Personal Project...
This is an example of static Proxy.




Java's built-in support for Proxy can build a dynamic proxy class on demand and dispatch all calls on it to a handler of your choosing.
Like any wrapper, proxy will increase the number of classes and objects in your designs.
Rules of thumb
1. Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface. [GoF. p216]
2. Decorator and Proxy have different 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]
3. Proxy controls access to objects . But Decorator decorates the objects by adding behaviour to them.

Strategy vs State Design Patterns.

1. State: Encapsulate interchangable behaviours and use delegation to decide which behaviour to use.
Strategy: Subclasses decide how to implement steps in an algorithm.
2. With State Pattern we have a set of behaviours encapsulated in state objects; at any time the context is delegating to one of those states. Over time, the current state changes across the set of state objecs to reflect the internal state of context, so the context's behaviour changes over time as well. The client usually knows very little, if anything about the state objects.
With Strategy, the client usually specifies the strategy object that the context is composed with. Now, while the pattern provides the flexibility to change the strategy object at runtime, often there is a strategy object that is most appropriate for a context object.
3. Think of the State Pattern as an alternative to putting lots of conditionals in your context; by encapsulating the behaviours within state objects, you can simply change the state object in context to change its behaviour.

State Design Pattern

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class
What does it mean for an object to "appear to change its class?" Think about it from the perspective of a client: if an object you are using can completely change its behavior, then it appears to you that the object is actually instantiated from another class. In reality, however you know that we are using composition to give the appearance of a class change by simply referencing different state objects.
Motivation
  • State charts are often used to describe dynamic behavior
  • The "traditional" way to implement state transitions often involves complicated, nested if statements
      For example the behaviour of an object Room's isDark() is different when the values of property light changes.
public boolean isDark()
{
if(swichLight().equalsIgnoreCase("off"))
return true;
else
return false;
}


Let us look at detailed example:
Consider the life of a person, it has 4 states - childhood, boyhood, youth and old-age. So
now if you are youth, you do something different and when you are boy you do different.
So the logic uses nested ifs to find what the state is and then perform logic.
//With out using StateDesign Pattern



public class Life
{
final static int CHILD = 0;
final static int BOY = 1;
final static int YOUTH = 2;
final static int OLD = 3;

int state = CHILD;

public void children(){
if(state == CHILD){
System.out.println("Go and Play...");
state = BOY;
}
else if(state == BOY)
System.out.println("Don't behave like a kid");
else if(state == YOUTH)
System.out.println("Don't behave like a kid");
else if(state == OLD)
System.out.println("Don't behave like a kid");
}

public void schoolBoy(){
if(state == CHILD)
System.out.println("grow up...");
else if(state == BOY){
System.out.println("Its time to go to school");
state = YOUTH;
}
else if(state == YOUTH)
System.out.println("Don't behave like a boy");
else if(state == OLD)
System.out.println("Don't behave like a boy");
}

public void youngGeneration(){
if(state == CHILD)
System.out.println("grow up...");
else if(state == BOY)
System.out.println("grow up...");
else if(state == YOUTH){
System.out.println("Right time to achieve my goals...");
state = OLD;
}
else if(state == OLD)
System.out.println("You are no longer youth");
}

public void oldGeneration(){
if(state == CHILD)
System.out.println("grow up...");
else if(state == BOY)
System.out.println("grow up...");
else if(state == YOUTH){
System.out.println("grow up...");
state = OLD;
}
else if(state == OLD)
System.out.println("I can guide you all");
}

public String toString(){
return state+"";
}

// Other methods...
}

The State Pattern
  • Delegate the responsibility of handling state transitions to encapsulations of the states
  • Participants:
    • An abstract State  
    • Several concrete State classes
    • A Context
By encapsulating each state into a class, we localize any changes that will need to be made.
State transitions can be controlled by State Classes or by Context Classes.

Objects are often discussed in terms of having a "state" that describes their exact conditions in a given time, based upon the values of their properties. The particular values of the properties affect the object's behavior.

Now if we use State Design Pattern here, we can get rid of this messy if else code in Life Class and also make it flexible.

//With State Design Pattern


public interface State{
public void childhood();
public void boyhood();
public void youth();
public void old();
}




public class ChildHoodState implements State{

Life life;

public ChildHoodState(Life life){
this.life = life;
}

public void childhood(){
System.out.println("Go and Play...");
life.setState(life.boyHoodState);
}
public void boyhood(){
System.out.println("Don't behave like a kid");
}
public void youth(){
System.out.println("Don't behave like a kid");
}
public void old(){
System.out.println("Don't behave like a kid");
}
}




public class BoyHoodState implements State{

Life life;

public BoyHoodState(Life life){
this.life = life;
}

public void childhood(){
System.out.println("Grow up.. ");
}
public void boyhood(){
System.out.println("Its time to go to school");
life.setState(life.youthState);
}
public void youth(){
System.out.println("Don't behave like a boy");
}
public void old(){
System.out.println("Don't behave like a boy");
}
}




public class YouthState implements State{

Life life;

public YouthState(Life life){
this.life = life;
}

public void childhood(){
System.out.println("Grow up...");
}
public void boyhood(){
System.out.println("Grow up...");
}
public void youth(){
System.out.println("Right time to achieve my goals...");
life.setState(life.oldState);
}
public void old(){
System.out.println("You are no longer youth");
}
}




public class OldState implements State{

Life life;

public OldState(Life life){
this.life = life;
}

public void childhood(){
System.out.println("Grow up...");
}
public void boyhood(){
System.out.println("Grow up...");
}
public void youth(){
System.out.println("Grow up...");
}
public void old(){
System.out.println("I can guide you all");
}
}




public class Life{
// All the States
State childHoodState;
State boyHoodState;
State youthState;
State oldState;

// initialise them
State state = childHoodState;

public Life(){
childHoodState = new ChildHoodState(this);
boyHoodState = new BoyHoodState(this);
youthState = new YouthState(this);
oldState = new OldState(this);
}

// Delegate to current state

public void children(){
state.childhood();
}

public void schoolBoy(){
state.boyhood();
}

public void youngGeneration(){
state.youth();
}

public void oldGeneration(){
state.old();
}

// for transition of state
public void setState(State state){
this.state = state;
}

// Many other methods needed... including getters and setters of each State

}




public class TestLife{
public static void main(String[] args) {
Life life = new Life();
System.out.println(life);

life.children();
life.schoolBoy();
life.youngGeneration();
life.oldGeneration();

System.out.println(life);


}
}


What we are doing here is implementing the behaviours that are appropriate for the state we are in. In some cases this behaviour includes moving the Life forward to new state.
We will have similar kind of classes for 'YouthState' and 'OldState' also ...
From the above explanation we came to know that State Design Pattern is a fully encapsulated, self-modifying Strategy Design Pattern.

Advantage and Disadvantage

In general think of strategy pattern as a flexible alternative to subclassing; if you use inheritence to define the behaviour of a subclass then you are stuck with that behaviour even if you need to change it. With Strategy you can change the behaviour by composing with a different object.
Disadvantage: By encapsulating state behaviour into seperate classes, you'll always end up with more classes in your design. That's often the price you pay for flexibility.

Composite Pattern in Java

Composite allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Whenever we have a requirement of handling all the objects in the same structure we can go for composite pattern, where we can create a tree structure that contain both composition of objects and individual objects as nodes and treat all of them uniformly by using same operations.
A Composite contains components i.e.(composites(again can contain components) and leaf elements(cannot contain components again)).
Base Component defines an interface for all objects in the composition. The Client uses this base component class to deal with the objects in the composition. It may also provide the default behaviour for adding,removing or accessing child components. But mostly Component is an interface.
Composite: Defines beahviour of components having children and stores the child components. We can add and remove Component instances to this composite dynamically.
Leaf : Defines the behaviour for the elements in the composition. It doesn't have references to other Components
First we need to have a Component Interface.(BaseComponent where even you can give some default implementation also)

//Component
public interface Component {
public void add(Component countryComponent);
public void remove(Component countryComponent);
public Component getChild(int i);
public String getName();
public String getDescription();
public void print();
}



Then we have Leaf implementation, which further does'nt have references to other components.


//Leaf
public class Leaf implements Component{
private String name;
private String description;

public Leaf(String name,String description){
this.name = name;
this.description = description;
}

/* these three methods doesn't make
* sense for Leaf. So we can even make
* the Base Component as abstract Class
* and provide the default implementation
* instead of this approach.
*/

public void add(Component state){
System.out.println("Sorry, leaf can't have components ");
}

public void remove(Component state){
System.out.println("Sorry, leaf can't have components ");
}

public Component getChild(int i){
System.out.println("Sorry, leaf can't have components ");
throw new UnsupportedOperationException();
}

public void print(){
System.out.println("-------------");
System.out.println("Name ="+getName());
System.out.println("Description ="+getDescription());
System.out.println("-------------");
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}



and finally the Composite Implementation which again can contain child components.


// Composite
public class Composite implements Component{
private String name;
private String description;

// list of State Components
List<Component> components = new ArrayList<Component>();

public Composite(String name, String description){
this.name = name;
this.description = description;
}

public void add(Component state){
components.add(state);
}

public void remove(Component state){
components.remove(state);
}

public Component getChild(int i){
return components.get(i);
}
public void print(){
System.out.println("-------------");
System.out.println("Name ="+getName());
System.out.println("Description ="+getDescription());
System.out.println("-------------");
Iterator<Component> iterator = components.iterator();
while(iterator.hasNext()){
Component component = iterator.next();
component.print();
}
}

public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}


}




public class Test {
public static void main(String[] args) {
Component leaf = new Leaf("leaf","No components futher");
Component composite = new Composite("composite","Again has components");
Component subcomposite = new Composite("subcomposite","Sub Composite again contain components");

Component baseComponent = new Composite("BaseComponent","Includes all other components");

baseComponent.add(leaf);
baseComponent.add(composite);
baseComponent.add(subcomposite);

baseComponent.print();
}
}


A general consideration when implementing this pattern is whether each component should have a reference to its
container (composite). The benefit of such a reference is that it eases the traversal of the tree, but it also decreases your flexibility.
There are many tradeoffs in implementing Composite. You need to balance transperency and safety with your needs.
Hope this explanation helps.
References : Applied Java Patterns by Stephen Stelting and Olav Maassen

Iterator Pattern in Java

Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
It also places the task of traversal on the iterator object, not on the aggregate, which simplifies the aggregate interface and implementation and places the responsibility where it should be.
One Real time example of Iterator Pattern is the usage of Remote Controls in Home. This example I came accross when I was reading my husband's blog and found very intresting. I will share the same example with you.
Any Remote Control we use to start pressing up and down and back keys to iterate through the channels.

public interface Iterator {
public Channel nextChannel(int currentChannel);
public Channel previousChannel(int currentChannel);
}


The Channel iterator is common for all the remote controls.It's like a specification implemented by all the remote control manufacturing companies.


public class ChannelSurfer implements Iterator{
public Channel nextChannel(int currentChannel) {
Channel channel=new Channel(currentChannel+1);
return channel;
}
public Channel previousChannel(int currentChannel) {
Channel channel=new Channel(currentChannel-1);
return channel;
}
}


public class RemoteControl {
private ChannelSurfer surfer;
public RemoteControl() {
surfer=new ChannelSurfer();
}
public Program getProgram(ChannelSurfer surfer) {
return new Program(surfer.nextChannel());
}
}

public class Program {// ... Some specific implementation of Program class.}
}


We all know that every channel is associated with program and it's basically the program and not the channel number which a user wants to see.This applies that we can apply some logic before returning the elements through iterator.Iterator here can also be programmed to return 'the programs' straight away rather than returning the channels.
Common Java Iterator is Iterator itself.Interface Signature has been copied from the javadoc.
An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:
-> Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
-> Method names have been improved.

public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}


java.util.Collection interface a root interface in Collections hierarchy contains a method iterator() which returns the Iterator interface.
Hence any class implementing Collection interface should provide definition for iterator() method.But please note that there are no Guarantees concerning the order(unless this collection is an instance of some class that provides a guarantee) as List by definition guarantees ordered Collection.
When we try to view List interface which extends Collection interface it has a method iterator() which returns an Iterator over the elements in this list in proper sequence.
Now coming to ArrayList a subclass class implementing List interface - which also extends AbstractList class provides definition for iterator() method.Infact all the underlying logic sits in AbstractList class.
When we try to view code it tries to return a Itr innerClass object.

public Iterator<E> iterator() {
return new Itr();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}

 

Other Patterns



Composite Pattern
Iterators are often used to recursively traverse composite structures.
Factory Method
Polymorphic iterators use factory methods to instantiate the appropriate iterator subclass.

Single Responsibility Principle (SRP)

The Single Responsibility Principle.
  • Each responsibility should be a separate class, because each responsibility is an axis of change.
  • A class should have one, and only one, reason to change.
  • If a change to the business rules causes a class to change, then a change to the database schema, GUI, report format, or any other segment of the system should not force that class to change.
So in brief, principle states: There should never be more than one reason for a class to change. Below is an example of some code breaking this principle.

Case 1 : Violating SRP


 
public class WeatherDisplay
{
private int _Temperature;
private int _WindSpeed;

public WeatherDisplay(int temperature, int windSpeed)
{
_Temperature = temperature;
_WindSpeed = windSpeed;
}

public void DisplayWeather()
{
DisplayTemperature();
DisplayWindSpeed();
}

private void DisplayTemperature()
{
println("The current temperature is: " + _Temperature + " degrees celcius.");
}
private void DisplayWindSpeed()
{
println("The current wind speed is: " + _WindSpeed + " meters per second.");
}
}





As you can see there are 2 distinct responsibilities for the class WeatherDisplay (you could even say there are 3 responsibilities). You could say one is to display the temperature and the other is to display the wind speed. Now because we are talking about 2 responsibilities we can also say that there are at least 2 reasons why we would / could change this class in the future, the temperature should be displayed in Fahrenheit and the wind speed should be displayed in knots.

Case 2 : Following SRP


Below we see how we could solve this and be coding according to the Single Responsibility Principle.
WeatherDisplay

public class WeatherDisplay
{
private DisplayTemperature _DisplayTemperature;
private DisplayWindSpeed _DisplayWindSpeed;

public WeatherDisplay(int temperature, int windSpeed)
{
_DisplayTemperature = new DisplayTemperature(temperature);
_DisplayWindSpeed = new DisplayWindSpeed(windSpeed);
}

public void DisplayWeather()
{
_DisplayTemperature.Display();
_DisplayWindSpeed.Display();
}
}
}

TemperatureDisplay

public class DisplayTemperature
{
private int _Temperature;

public DisplayTemperature(int temperature)
{
_Temperature = temperature;
}

public void Display()
{
println("The current temperature is: " +
_Temperature + " degrees celcius.");
}
}

WindSpeedDisplay
public class DisplayWindSpeed
{
private int _WindSpeed;

public DisplayWindSpeed(int windSpeed)
{
_WindSpeed = windSpeed;
}

public void Display()
{
println("The current wind speed is: " +
_WindSpeed + " meters per second.");
}
}

In this second example you can see that I now re-factored the class WeatherDisplay into three classes. Weather Display still exists but now it is using the class TemperatureDisplay and WindSpeedDisplay to actually display the data.

 

Case 3 : Better implementation


As I said before you could even say that there were 3 responsibilities for the first example and they would be displaying the information, providing temperature text markup and providing wind speed text markup. So in that case we would probably re-factor our example in the following way:

Interface: ITextDisplay

public interface ITextDisplay  {
void Display(TextWriter writer);
}
DisplayTemperature

public class TemperatureDisplay implements ITextDisplay
{
private int _Temperature;

public TemperatureDisplay(int temperature)
{
_Temperature = temperature;
}

public void Display(TextWriter writer)
{
writer.WriteLine("The current temperature is: " + _Temperature + " degrees celcius.");
}
}

DisplayWindSpeed


public class WindSpeedDisplay implements ITextDisplay
{
private int _WindSpeed;

public WindSpeedDisplay(int windSpeed)
{
_WindSpeed = windSpeed;
}

public void Display(TextWriter writer)
{
writer.WriteLine("The current wind speed is: " + _WindSpeed + " meters per second.");
}
}

As you can see now instead of providing the class WeatherDisplay with a fixed number of parameters we can now provide it with an unlimited amount of ITextDisplay implementations. The class WeatherDisplay is now responsible for providing a proper TextWriter and telling each ITextDisplay implementation to display its information. The ITextDisplay implementations now only have to write its information to the provided writer, and thus also implementing the Liskov Substitution Principle.



Template Method Pattern

Template method defines the skeleton of Algorithm(steps of algorithm) in a method, differing some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
The objective is to ensure that algorithm's structure stays unchanged, while subclasses provide some part of implementation.

This pattern is all about creating a template for an algorithm. Here Template is nothing but a method; more specifically it is a method that defines an algorithm as a set of steps.
Let us look at an example :

abstract class Generalization {
// 1. Standardize the skeleton of an algorithm in a
//"template" method
public final void findSolution() {
stepOne();
stepTwo();
stepThr();
hook();
}
// 2. Common implementations of individual steps are defined
//in base class
protected void stepOne() {
System.out.println( "Generalization.stepOne (Common)" );
}
// 3. Steps requiring particular impls are "placeholders"
//in the base class
abstract protected void stepTwo();
abstract protected void stepThr();
// 4. This is hook method (concrete method) which
//provides default implementation, but
//allows subclasses to override if necessary.
protected void hook() {
System.out.println( "This is default
implementation of hook method"
);
}
}
class SpecializationOne extends Generalization {
// 5. Derived classes can override placeholder methods
protected void stepThr() {
System.out.println( "SpecializationOne.stepThr" );
}
protected void stepTwo() {
System.out.println( "SpecializationOne.stepTwo" );
}
}
class SpecializationTwo extends Generalization{
// 5. Derived classes can override placeholder methods
protected void stepTwo() {
System.out.println( "SpecializationTwo .stepTwo" );
}
protected void stepThr() {
System.out.println( "SpecializationTwo.stepThr" );
}
protected void hook() {
System.out.println( "SpecializationTwo.hook" );
}
}


Hook is a method that is declared in abstract class, but only given empty or default implementation. This gives the subclasses the ability to hook into the algorithm at various points, if they wish. Subclass is also free to ignore the hook method.
When to use abstract method and when to use hooks?
Use abstract methods when your subclass must provide the implementation. Choose hook when it is optional for subclasses to implement it.



Hollywood Priciple:



Don't call us we will call you.
Hollywood Priciple allows us to prevent dependency rot.
With the hollywood priciple, we allow low level components to hook themselves into a system. But high level components decide when they are needed and how... In other words high level components give 'don't call us, we will call you' treatment to low level components.
The connection between Hollywood Principle and Template Method Pattern is probably somewhat apparent.
In our above example Generalization is our high-level component. It has control over the sequence of methods to be called and calls on the subclasses only when they are needed for implementation of a method.
Client will depend on Generalization rather than concrete SpecializationOne or SpecializationTwo which reduces dependencies in overall system.
The subclasses never call abstract class directly without being 'called' first.




Difference between Dependency Inversion Principle and Hollywood Principle
Dependency Inversion principle tells us to avoid use of concrete classes and instead work as much as possible with abstractions.
The Hollywood princple is a technique for building frameworks or components so that lower level components can be hooked into computation but without creating dependencies between lower level components and higher level layers.
So they both have goal of decoupling but Dependency Inversion Principle makes a strong and general statement about how to avoid dependencies in design.
The Hollywood principle gives us a technique for creating designs that allow low level structures to interoperate while preventing other classes from becoming too dependent on them.




Advantages of Using The Template Method Design Pattern
1. No code duplication between the classes
2. Inheritance and Not Composition
Whenever a design pattern uses inheritance as a key element instead of composition, you need to consider the reason. To understand the reason, you need to fully understand the principle of favoring composition over inheritance as a general principle in good OOP. The principle's established because of certain advantages of composition over inheritance, especially the composition advantage of not breaking encapsulation. However, Gamma, Helm, Johnson and Vlissides (GoF) note that inheritance also has certain advantages. One such advantage is that when using subclasses where some but not all operations are overridden, modifying the reused implementation is easier. Because the Template Method design pattern does exactly that—uses some but not all operations that can be overridden to achieve flexibility—it incorporates a key advantage of inheritance over composition.
3. By taking advantage of polymorphism the superclass automatically calls the methods of the correct subclasses.


Comparision of different Patterns:
Template Method Pattern : Subclasses decide how to implement steps in an algorithm.
Strategy Pattern : Encapsulates interchangable behaviours and use delegation to decide which behaviour to use.
Factory Method: Subclasses decide which concrete classes to create.

Facade Pattern

Facade provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easy to use.

Facade pattern works on principle of least knowledge.

A Facade not only simplifies an interface, it also decouples a client from subsytem of components. Using Facade Pattern you can take a complex subsystem and make it easier to use by implementing a Facade class that provides resonable interface.

Need for Facade


For Example,Let us think we have subsytem containing Gate, GarageDoors, CarLock, Lights etc.. Now when we leave home we have to following:

door.open();
lights.off();
door.close();
garageDoor.open();
carLock.unlock();
gate.open();
garageDoor.close();
gate.close();


This is a small subsystem, but consider you have bungalow, things get more complicated. Not only this, when the person comes back , he has to do following things:


gate.open();
garageDoor.open();
carLock.lock();
door.open();
lights.on();
gate.close();
garageDoor.close();
door.close();

Again a hell lot of work. Wouldn't be it good, if we have some smart system, which does all this itself, rather than we go and click all these to work. This is where facade pattern comes into picture.

Instead of doing all that stuff and making lots of object in our main class, we supply all these components to our facade class, which deals with these components and solve these problems. Now we will be having a single iterface which will do simplify the subsystem for us:


public class HomeFacade{
Gate gate;
GarageDoor garageDoor;
CarLock carLock;
Lights lights;
MainDoor door;

public HomeFacade(Gate gate,GarageDoor garageDoor,CarLock carLock,Lights lights,MainDoor door){
this.gate = gate;
this.garageDoor = garageDoor;
this.carLock = carLock;
this.lights = lights;
this.door = door;
}

public void reachHome(){
gate.open();
garageDoor.open();
carLock.lock();
door.open();
lights.on();
gate.close();
garageDoor.close();
door.close();
}

public void leaveHome(){
door.open();
lights.off();
door.close();
garageDoor.open();
carLock.unlock();
gate.open();
garageDoor.close();
gate.close();

}
}


The Facade still leaves the subsystem accessible to be used directly. If you need the advanced functionality of the subsystem classes, they are avilable for your use. (As Facade doesn't encapsulate the subsystem classes, but it provides a simplified interface)
Facade is free to add its own specialization in addition to making use of subsystem.
For a subsystem, we can have number of Facades.


Design Principle behind Facade pattern :



Priciple of least knowledge : When you are designing a system, for any object be careful of the number of classes it interacts with and also how it interacts with those classes. Also known as law of Demeter.
This principle prevents us from creating designs that have a large number of classes coupled together so that changes in one part of the system cascade to other parts. when you build a lot of dependencies between many classes, you are building a fragile system that is costly to maintain and complex for others to understand.
But how to implement this design priciple?
Take any object. Now from any method in that object, we should only invoke methods that belong to
1. The Object itself
2. Objects passed in as a parameter to the methods
3. Any object that method creates and instantiates.
4. Any components of objects. (Has-A relationship)
(Dont call methods on objects that were returned from calling other methods)
Example :



Without principle :


public float applyForJob(){
Agency agency = company.getAgency();
return agency.searchJob();
}


Here we are dependent on Agency Class also



With principle:


public float applyForJob(){
return company.searchJob();
}



This reduces the number of classes we are dependent on.
Primary benifit is that the calling method doesn't need to understand structural makeup of the object it's invoking methods upon.
The obvious disadvantage of using this principle is that we must create many methods that only forward method calls to the containing classes internal components. This can contribute to a large and cumbersome public interface.
An alternative to this principle or variation on its implementation, is to obtain a reference to an object via a method call, with the restriction that any time this is done, the type of reference obtained is always an interface datatype. As we are binding ourselves with directly to the concrete implementation of a complex object, but instead we are depending on abstractions of which the complex object is composed.


A very nice example of the above approach is java.sql.ResultSet interface.
After an SQL statement has been executed, Java stores results in a ResultSet Object. One of our options at this point is to query this resultset object and obtain metainformation pertaining to this set of data. The class that contains this metadata is ResultSetMetaData class and it's contained with resultset class. We cant directly obtain reference of this class, but instead would call methods on the ResultSet which subsequently forward these requests to ResultSetMetaData Class. This would results in explosion of methods on ResultSet class. Therefore getResultSetMetaData() method on ResultSet would does return a reference to ResultSetMetaData. However as ResultSetMetaData is an interface we are not bound to any concrete implementation contained within resultset.


Difference between Adapter pattern and facade Pattern:
Adapter Pattern changes the interface of one or more classes into one interface that a client is expecting while a Facade may provide a simplified interface to a single class with a very complex interface.
Facade and Adapter may wrap multiple classes but facade's intent is to simplify and adapter's intent is to convert the interface to something different.
Hope it will be useful.