Showing posts with label Design. Show all posts
Showing posts with label Design. Show all posts

Friday, February 6, 2009

Design - Singleton Pattern

JVM is a virtual machine where you find threads, objects, classes, classloaders, garbage collector etc having their own living space in the machine. Of all these it is the threads which keeps the metabolism going. When all the threads are dead the virtual machine dies. During its lifetime these threads create, edit or act upon multiple objects. Objects hold data and defines the behavior. In certain instances we need specialized objects holding data which needs to be shared across the virtual machine. This requires us to maintain only one instance of the object which is shared across multiple threads in the jvm. This is defined by Singleton pattern. Below are my thoughts and understandings of this pattern.

The basic definition of this pattern is as below.
1. Make the object constructor private. This allows the control on object creation.
2. Define the static object reference to self to hold the instance of this object.
3. Define the static getter method to get a reference to the object.
There are many flavors of pattern implementation, which are as below.

A. A very simple way of implementing Singleton is as below. This works in both the situations of single and multi-threaded environment.
public class Singleton{
private static final Singleton instance = new Singleton();
//Other data attributes go here...
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
//Other methods go here...
}

The above method is simple and very effective, but this may not be desirable in few design situations. The above method does early initialization of the object while the below methods talk about the lazy initializations.

B. When more control is needed, like handling the situations when the initialization in the constructor throwing exception. Though exception may be handled in the constructor or a new exception can be thrown from constructor, we may want to return null value to the to the calling method rather than return this partially initialized instance.
//CASE: Single threaded environment:
public class Singleton{
private static Singleton instance = null;
//Other data attributes go here...
private Singleton(){}
public static Singleton getInstance(){
if(instance = null) instance = new Singleton();
return instance;
}
//Other methods go here...
}
//CASE: Multi threaded environment
public class Singleton{
private static Singleton instance = null;
//Other data attributes go here...
private Singleton(){}
private static synchronized Singleton createInstance(){
if(instance == null){
//Exception handling can be done here.
instance = new Singleton();
}
return instance;
}
public static Singleton getInstance(){
Singleton singleton = instance;
if(singleton = null){
singleton = createInstance();
}
return singleton;
}
//Other methods go here...
}

C. There is also the other reason why we may not do the early initialization. If we wish to extend from the Singleton class. Below style talks of this in the multi threaded environment.
//CASE: Parent:
public class Singleton{
protected static Singleton instance = null;
//Other data attributes go here...
protected Singleton(){}
private static synchronized Singleton createInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
public static Singleton getInstance(){
Singleton singleton = instance;
if(singleton = null){
singleton = createInstance();
}
return singleton;
}
//Other methods go here...
}
//CASE: Child
public class ChildSingleton extends Singleton{
//Other data attributes go here...
protected ChildSingleton(){}
private static synchronized Singleton createInstance(){
//Overriding the createInstance behaviour
if(instance == null){
instance = new ChildSingleton();
}
return instance;
}
//Other methods go here...
}

However be careful in the above method as the protected access specifier indicates that it can be accessed by the other classes in the same package as well, which gives a leak to create multiple instances.

D.One of the good approaches I have come across. This works well in all situations and is lazy initialization as well.
public class Singleton{
//Other data attributes go here...
private Singleton(){}

public static Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
//Other methods go here...

//Inner class
private static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
}
}

But beware that Singleton may not really be a single instance and there can be many leaks. There are some more good articles on this topic. Few of them are mentioned below.
http://en.wikipedia.org/wiki/Singleton_pattern
http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html

Wednesday, June 25, 2008

UML - Building Blocks

UML defines how the system or application can be represented visually in number of diagrams. The System's design is basically made of diagrams and the diagrams contain many related elements. A system's architecture and specification is shown with multiple diagrams. There are various diagrams which UML defines which can be used to show the system at various levels and views. All the diagrams and the elements in it constitute the model of the software system or application. The model is nothing but the blueprint of the system.

To understand UML, one needs to understand basic building blocks, rules guiding them and the common design concepts.

The building blocks (vocabulary of language) of UML are:
1. Things
2. Relationships
3. Diagrams
Lets go one by one to get a better picture...

Things are the elements of UML model which is used to build a model
There are four kinds of things in the UML
i) Structural things (nouns) - Classes, Interfaces, Collaborations, Use Cases, Active Classes, components and nodes
ii) Behavioral things (verbs) - Interaction (messages exchanged), State machine
iii) Grouping things (organisation of structural things) - Package
iv) Annotational things (documentation) - Annotations

Relationships are the elements which indicate how two or more things are related to each other. There are various relationships, which are:
i) Dependency (semantic relation) - indicates that change to one thing may affect the semantics of other thing. One of the commonly seen relation is Use-Dependency, where one thing uses other thing to perform certain action.
ii) Association (structural relation) - indicates whole and its part relationship
iii) Generalization (inheritence relation) - the specialized element (the child) are substitutable for objects of generalized element (the parent). In this way the child shares the structure and behavior of the parent.
iv) Realization - one classifier specifies the contract that another classifier gaurantees to carry out. This relationship can be found in two places: between interfaces and the classes or components that realize them, and between use cases and the collaborations that realize them.

Diagrams are the graphical representation using things and relationships to visualize a system with specific perspective. So a diagram is a projection into a system. In theory, a diagram may contain any combination of things and relationships. In Practice, however, a small number of common combinations arise, which are consistent with five most useful views that comprise the architecture of a software-intensive system. In UML1.0 there are nine such diagrams supporting this.
1. Class Diagram
2. Object Diagram
3. Use Case Diagram
4. Sequence Diagram
5. Collaboration Diagram
6. Statechart Diagram
7. Activity Diagram
8. Component Diagram
9. Deployment Diagram

Out of these Class Diagrams, Object Diagrams, Component Diagrams and Deployment Diagrams indicate the structural specification of the software system and the rest of the diagrams are useful in projecting the behaviour of the system.

Wednesday, April 23, 2008

UML - Why?

The so called "Programming World" started much before the world's first single chip microprocessor, Intel 4004 was invented in November, 1971. It has been evolving since then, with newer paradigms seeding the birth of new languages. As the computing power of the processors increasing at a rapid pace from 8085, 80x86, etc, the programming languages are able to stretch themselves making the language more flexible, efficient and readable. Today, robots are being programmed to understand not just the syntax and semantics but also the pragmatics of the language. Let us not get that far but try to understand where the current programming languages are leading to. For those who are interested in the chronology of languages they can take a look at this site http://www.scriptol.org/history.php.

Broadly the programming styles can be categorized into two: Imperative and Declarative (See http://en.wikipedia.org/wiki/Programming_paradigm for more paradigms). Every language is basically a set of language grammar which the language compiler translates to machine understandable instructions.

Most of the languages which were used for development were typed and with the increasing complexity of software development, there arose a necessity for a language which a human can easily understand. The advent of Object Oriented paradigm helped in this direction with the concepts of objects and behavior similar to the real world objects. During 1990's UML or Unified Modeling Language took birth gradually with the union of ideas from three people Grady Booch, Jim Rumbaugh, and Ivar Jacobson. This language gave a visual representation of the system from various aspects which even an average programmer could easily understand. By being able to put it into diagrams, UML eased the software development to a great extent. With the various views and diagrams of the system one could easily get both the bigger picture as well as the surgical view of the system. In general UML introduced a standardized visual specification for object modeling.

Now lets talk about the need and how UML helps.
In the current situation,


Interested ones can look at the more links below,
UML History graph: http://en.wikipedia.org/wiki/File:OO-historie.jpg
UML Specifications: http://www.omg.org/technology/documents/modeling_spec_catalog.htm#UML

Learning programming

    Programming is an interesting world where you apply your skills to build a software program that comes into life when it is run on a com...