CSC/ECE 517 Fall 2012/ch2b 2w53 iv: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 226: Line 226:




10. [bosy.dailydev.org/2007/08/refactor-singleton-out-of-your-code.html Refactor Singleton Out Of Your Code]
10. [http://bosy.dailydev.org/2007/08/refactor-singleton-out-of-your-code.html Refactor Singleton Out Of Your Code]


'''Topics Covered''' :
'''Topics Covered''' :

Revision as of 00:05, 19 November 2012

Singleton, directory of sites

Singleton, directory of sites Pattern

1. Singleton on the Wikipedia

Topics Covered : Common uses, UML, Implementation, Example, Prototype based singleton, Example of use with factory method pattern

Summary : This link firstly provides the basic definition of the singleton pattern as a design pattern that restricts the instantiation of a class to one object. Singleton patters are mostly used in Abstract Factory, Builder, and Prototype, and Facade patterns.

Both the UML representation of singleton where the same single instance is always returned and the implementation concerning the mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among the class objects. The link also points out that if a class has to realize a contract expressed by an interface, it really has to be a singleton.

Lazy initialization uses double-checking and eager initialization which always creates an instance. For instance, Lazy initialization and Eager Initialization example codes are: Lazy Initialization:

public class SingletonDemo {
private static volatile SingletonDemo instance = null;
private SingletonDemo() {}
public static SingletonDemo getInstance() {
if (instance == null) {
  synchronized (SingletonDemo .class){
  if (instance == null) {
  instance = new SingletonDemo ();
                      }
                   }
              }
return instance;
}
}

Eager Initialization:

public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}

It also talks about Prototype-based programming in which objects but not classes are used, a 'singleton' simply refers to an object without copies or that is not used as the prototype for any other object. Eg :->

Foo := Object clone 
Foo clone := Foo

Drawbacks : The pattern makes unit testing far more difficult as it introduces global state into an application. It should also be noted that this pattern reduces the potential for parallelism within a program, because access to the singleton in a multi-threaded context must be serialized.

2. Learn Singleton-design-Pattern

Topics Covered : Definition, When to use, how to create, Sharing across all users, Sharing across a request, Sharing across a single user

Summary : This article explains what Singleton pattern is, what kind of problem it generally solves and how should it be implemented in ASP.NET. The Singleton pattern which ensures that only one instance of a given object can exist at a context solves problems related to object creation and hence is a type of creational pattern.

It can be used in a class that wraps the settings related to an application. In other words, whenever we want something to be shared across multiple locations, we use a singleton pattern. In order to create a Singleton pattern, we can render the constructor private so that no user can create a new instance outside the class, that way ensuring only one instance of the objects always exists. In that case, we also need to create a static method that returns the single object.

Singleton patterns in ASP.NET are implemented by using static objects which maintain their values and reside in the memory as long as the application which contains it does. The sharing can occur across users, or requests or across a single user.

3. Singleton - Creational Design Pattern

Topics Covered : Intent, Description, An Example, Implementation, Benefits

Summary : It firstly talks about the intent behind singleton design pattern, in that there is a need to have a class that can be instantiated only once. Then, it describes two solutions for implementing the singleton class. In the first, there should be only one shared object and reference to that shared object should be available through a static method GetInstance() while the constructor is private. The second solution expects the constructor to be public but once an object has been instantiated, an exception should be thrown for each successive constructor call.

The code for each case is given as follows:

Case 1 :

class Singleton
{
private static Singleton instance;
private static int numOfReference;
private string code;
private Singleton()
{
numOfReference = 0;
code = "Maasoom Faraz";
}
public static Singleton GetInstance()
{
if(instance == null)
{
instance = new Singleton();
}
numOfReference++;
return instance;
}
public static int Reference
{
get { return numOfReference; }
}
public string Code
{
get { return code; }
set { code = value;}
}
}

The constructor is made private and used to initialize the numOfReference and default value of code. GetInstance() method checks the instance, if it is null then it assign it an instance of Singleton otherwise return the old reference.

Case 2 :

class Singleton2
{
private static int numOfInstance = 0;
public Singleton2()
{
if(numOfInstance == 0)
{
Console.WriteLine("\r\nCreating First Object of Singleton2 class...");
numOfInstance++;
}
else
{
throw new Exception("This class is Singleton,
+ so only one object of it can be instantiated.");
}
}
}

Here we make the constructor public and use a private field numOfInstance which is incremented for each constructor call. If numOfInstance is zero (no object is yet instantiated), a new object is allowed to made. But, if this value is not zero (there is already an object of Singleton2 class, an exception is thrown.


\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/

1. Singleton explained on c2.com

Topics Covered : Simulation of global variables, Appropriate Use of Singleton, Singleton in threaded environment

Summary : This link firstly explains aspects like testing, creational logic,polymorphism involved in singleton pattern.It explains situations when singleton pattern can be used.It goes on to explain the anti-pattern of singletons simulating global variables and appropriate use of singleton in mutithreaded environment.

Problem of using Singleton in Multithreaded Environment :

static private synchronized Singleton instance_helper(){
_instance = new Singleton();
return _instance;
}

"_instance" can be null in the logic for multiple threads before instance_helper is called, leading to multiple instances being created

Solution for Singleton in Multithreaded Environment :

static private synchronized Singleton instance_helper()
{
if(flag)
{
_instance = new Singleton();
}
flag = false;
return _instance;
}

8. Singleton Applications

Topics Covered : Motivation, Intent, Implementation, Applicability and Examples

Summary : This link gives some extra information about applicability of Singleton in logger classes,configuration classes, accessing resources in shared environment,factories implemented as Singleton,Implementations and problems involved

Serialization :

If the Singleton class implements the java.io.Serializable interface, when a singleton is serialized and then deserialized more than once, there will be multiple instances of Singleton created. In order to avoid this the readResolve method should be implemented.

public class Singleton implements Serializable {
...
// This method is called immediately after an object of this class is deserialized.
// This method returns the singleton instance.
protected Object readResolve() {
return getInstance();
}
}


9. Singleton Implementation in C#

Topics Covered : Implementation in C#

Summary : This link explains how to implement a singleton in C# both in static and threaded environment.

Static Initialization:

One of the reasons Design Patterns [Gamma95] avoided static initialization is because the C++ specification left some ambiguity around the initialization order of static variables. Fortunately, the .NET Framework resolves this ambiguity through its handling of variable initialization:


public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get 
{ 
return instance; 
}
}
}


Implementing Singleton in C# results in the following benefits and liabilities:

Benefits:

  • The static initialization approach is possible because the .NET Framework explicitly defines how and when static variable initialization occurs.
  • The Double-Check Locking idiom described earlier in "Multithreaded Singleton" is implemented correctly in the common language runtime.

Liabilities: If your multithreaded application requires explicit initialization, you have to take precautions to avoid threading issues.


10. Refactor Singleton Out Of Your Code

Topics Covered : Solution to refactor singleton

Summary : Gang of Four mentions Singleton as an anti-pattern and not as a pattern. This Link provides a solution to refactor Singleton out of the code


Steps to refactor Singleton: 1. Create simple interface for Registry with two simple methods - getter and setter for instance of class which is currently implemented as singleton.

public interface ISingletonRegistry {
SingletonClass getSingletonClass();
void setSingletonClass(SingletonClass singleton);
}

2. Make SingletonClass's constructor public

3. Then implement the interface as a simplest Registry design pattern implementation - SingletonRegistry.

public class SingletonRegistry implements ISingletonRegistry {
private static final SingletonRegistry INSTANCE = new SingletonRegistry();
private SingletonClass singleton;
public static ISingletonRegistry getInstance() {
return INSTANCE;
}
private SingletonRegistry() {
//this is the reason why the constructor should be public
singleton = new SingletonClass();
}
public SingletonClass getSingletonClass() {
return singleton;
}
public void setSingletonClass(SingletonClass singleton) {
this.singleton = singleton;
}
}

4. Change getInstance method of SingletonClass to get instance from SingletonRegistry.

public static SingletonClass getInstance() {
return SingletonRegistry.getInstance().getSingletonClass();
}

5.The method getInstance from SingletonClass disappears and all it's client classes uses SingletonRegistry to access SingletonClass.

public class Client {
public void clientMethod() {
SingletonRegistry.getInstance() .getSingletonClass().voidMethod("param");
Object object = SingletonRegistry.getInstance() .getSingletonClass().objectMethod("param");
}
}

6. Delete INSTANCE constant from SingletonClass class.

7. You can Extract Interface (Alt+Shift+T, E) from SingletonClass. Write just new interface name, select all methods from SingletonClass which you can extract into new interface and press OK. All references to SingletonClass will be refactored to references to your newly created interface.

And that is all. Now you have SingletonClass with totally same functionality but you are able to mock it, extend or replace by different implementation setting up your instance of SingletonClass to SingletonRegistry.



<references />