Friday, April 29, 2011

Discussion on Design Pattern's..!



Singleton Pattern :-

Singleton Design Pattern is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system... Confused..!!.

Here goes the Example ?

1. objects needed for logging
2. communication
3. database access
4. file manager etc.

You could pass such an instance from method to method, or assign it to each object in the system.

When to Use ?

You should consider singleton design pattern in following scenario.!

A resource is shared across all application component and only one
instance of resource is possible.

Global variables are being passed across all part of application
Multiple instances representing same kind of information.

How to Use ?

It is pretty simple to implement this design pattern. Following are the key
requirements and possible solution for implementing singleton design pattern.

Only one instance should be available at the time – restrict the class
instantiation using private scoped constructor.

Everybody should get same instance – maintain a private static instance
variable so that only one instance will be available.

Example :-



1: namespace Singleton;
2: /**
3: * Singleton Resource Class
4: * @author Praveen Muniganti
5: */
6: public class SingletonResource {

7: private static SingletonResource resorce =null;

8:
9: public static SingletonResource getInstance(){
10: if(resorce==null){
11: resorce = new SingletonResource();
12: }
13: return resorce;
14: }
15:
16: private SingletonResource(){
17: // your initializing code here
18: }
19: }
20:

Main Class :
  
1: namespace Singleton;

2: public class SingletonTest {

3: static void main(String[] args){
4: SingletonResource resource1 = SingletonResource.getInstance();
5: SingletonResource resource2 = SingletonResource.getInstance();
6: if(resource1==resource2){
7: Console.WriteLine("Both are equals");
8: } else {
9: Console.WriteLine("Both are not equals");
10: }
11: }
12: }

Output : Both are equals





No comments:

Post a Comment