Alternatives to the Singleton Design Pattern
page 3 of 6
by Steven Smith
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 29286/ 42

Single Responsibility Principle

The Single Responsibility Principle is one of the fundamentals of object-oriented programming.  In essence, it states that a class or module should never have more than one reason to change.  The more things a class or module is charge of, the more kinds of change the class is affected by.  You can learn more about this and other related principles in my Principles of Object Oriented Design course on PluralSight On Demand.  Also be sure to check out the Software Craftsmanship 2011 Calendar, which includes SRP and 11 other important principles of writing better software and makes a great addition to your team room.

In the case of the Singleton pattern, the class is being given the extra responsibility, above and beyond whatever it actually does, of managing how many instances of itself are allowed to exist within the application.  This additional responsibility clearly violates SRP, and especially since there are so many ways to implement the Singleton pattern, and so many of these have negative consequences, my advice is to move the responsibility of managing the object's lifetime to a separate class with just this responsibility.  The simplest way to achieve this is through the use of an Inversion of Control Container, or IOC Container.


View Entire Article

User Comments

Title: Just use public static readonly   
Name: Ramon Smits
Date: 2010-12-08 7:42:43 PM
Comment:
Just use a public static readonly member. Easy, fast, lazy and threadsafe!

public class MyClass
{
public static readonly MyClass Instance = new MyClass();
private MyClass(){}
}

Much easier then this will be difficult to do!

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 5:46:00 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search