Wrapping non-static classes in a static container [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have a lot of manager classes which I use to access the database. I need to create an instance of a manager in order to access its methods.
Since I personally prefer static classes for this, I would like to know what you think of this approach:
public static class Managers
{
public static SomeManager Manager
{
get { return new SomeManager(); }
}
}
var stuff = Managers.SomeManager.DoStuff();
Any downsides?

The biggest downside to this is the lack of clarity to someone unfamiliar with your code: to me, a call like this
Managers.SomeManager.DoStuff();
means accessing SomeManager that is fixed in one way or the other, as opposed to
new SomeManager().DoStuff();
which tells me explicitly that SomeManager is being created on demand.
Converting SomeManager property into a method with an appropriate name, say, MakeSomeManager(), would restore readability:
Managers.MakeSomeManager().DoStuff();
You may want to do something like this in order to hide the process of instantiating SomeManager, the constructor of which may require some parameters that you are unwilling to carry around.

This is a bad implementation of the singleton pattern, as you are creating a new instance every time the property is called.
This would be better:
public static class Managers
{
private static SomeManager someManagerInstance;
public static SomeManager Manager
{
get
{
if (someManagerInstance == null)
{
someManagerInstance = new SomeManager();
}
return someManagerInstance;
}
}
}
Unless of course, that having a new instance every time is desired? In which case, I would wrap the creation in a method, rather than a property:
public static class Managers
{
public static SomeManager GetNewManager()
{
return new SomeManager();
}
}

Use the Singleton pattern. And if you're on .NET 4 or greater, the neatest (and 'laziest' version) is:
public sealed class SomeManager
{
private static readonly Lazy<SomeManager> lazy =
new Lazy<SomeManager>(() => new SomeManager());
public static SomeManager Instance { get { return lazy.Value; } }
private SomeManager()
{
}
}
Then access it via:
var stuff = SomeManager.Instance.DoStuff();
Implementing a thread-safe singleton has lots of pitfalls so you should check this out for some tips and examples.

You can use singleton instead, because using of static classes and methods like this is bad practice. For example try to write some unit tests for your implementation or else...
1) Create singleton class like this
public static class Singleton<T>
where T : class, new()
{
/// <summary>
/// The syncRoot.
/// </summary>
private static readonly object syncRoot = new object();
/// <summary>
/// The instance.
/// </summary>
private static volatile T instance;
/// <summary>
/// Gets the instance.
/// </summary>
public static T Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new T();
}
}
}
return instance;
}
}
}
2) Create your class like this
public class YourClass
{
/// <summary>
/// Singleton instance of
/// </summary>
public static YourClass Instance
{
get { return Singleton<YourClass>.Instance; }
}
...methods etc...
}
3) Call your singleton from code
YourClass.Instance.SomeMethodCall();

Related

Problem with an object pooling mechanism, Queue containing the pool can't be static because static variables aren't inherited

I'm setting up an object pooling mechanism in unity, basically how it works is:
You have a base abstract class called "Poolable", with a static queue containing objects in it (In this case GameObjects), there's a class called Projectile which inherits from Poolable as that's what i currently want to be pooled. It further extends to a Bullet class which inherits from Projectile, but the problem is, if i had an Arrow class which inherits from Projectile, it would use the same pool because the pool is static inside Poolable. Does anyone know a way i could tackle this issue?
I thought about making it non-static, but then the objects wouldn't know about the pool, they'd know about their own pool. Same with interfaces but they don't accept variables which aren't properties
The only current fix i see is adding it to each script that i use a pool on, but that then defeats the whole purpose of inheritance as i was trying to make a polymorphic-like structure where you'd have multiple poolables, multiple projectiles, maybe multiple bullets/arrows?
public abstract class Poolable : MonoBehaviour
{
protected static Queue<GameObject> objPool = new Queue<GameObject>(); // doesn't work because every poolable object will use this pool only
[SerializeField] protected GameObject prefab;
public GameObject Get()
{
if(objPool.Count == 0)
{
AddObjects();
}
return objPool.Dequeue();
}
protected void ReturnToPool(GameObject retObj)
{
objPool.Enqueue(retObj);
retObj.SetActive(false);
}
AddObjects()
{
}
}
If I am not mistaken, you need your object pool to be homogeneous. This means your pool contains only one type of object. For example, you don't want arrow and bullet to share the same pool even if they are all projectiles. We don't have c++'s decltype in c#, so if you want your object to have it's non-static member function ReturnToPool, you have to defer type evaluation to run-time (using a type dictionary). Here is the code that would possibly satisfy your need:
using System.Collections.Generic;
using UnityEngine;
using System;
public abstract class Poolable : MonoBehaviour
{
private static Dictionary<Type, Queue<Component>> objPool
= new Dictionary<Type, Queue<Component>>();
/// <summary>
/// Get an object from the pool; If fails, use the alternative method to create one
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="alternativeCreate"></param>
/// <returns></returns>
public static T Get<T>(Func<T> alternativeCreate) where T : Poolable
{
if (objPool.TryGetValue(typeof(T), out var queue) && queue.Count > 0)
{
var ret = queue.Dequeue() as T;
ret.Reactive();
return ret;
}
return alternativeCreate();
}
/// <summary>
/// Return the object to the pool
/// </summary>
public void ReturnToPool()
{
if (this.Reset())
{
var type = this.GetType();
Queue<Component> queue;
if (objPool.TryGetValue(type, out queue))
{
queue.Enqueue(this);
}
else
{
queue = new Queue<Component>();
queue.Enqueue(this);
objPool.Add(type, queue);
}
}
}
/// <summary>
/// Reset the object so it is ready to go into the object pool
/// </summary>
/// <returns>whether the reset is successful.</returns>
protected virtual bool Reset()
{
this.gameObject.SetActive(false);
return true;
}
/// <summary>
/// Reactive the object as it goes out of the object pool
/// </summary>
protected virtual void Reactivate()
{
this.gameObject.SetActive(true);
}
}
You should look into the Singleton Pattern. It's hard to suggest a suitable implementation for what you need because I don't know what you want to do with it, but basically, you can add something like this to your class:
private static Poolable _instance;
private static object _instanceLock = new Object();
public static Poolable Instance
{
get
{
if (_instance == null)
{
lock (_instanceLock)
{
if (_instance == null)
{
this._instance = [Whatever way you instantiate it];
}
}
}
return _instance;
}
}
Afterward, either make the constructor private/protected and make sure you always get your instance with Poolable.Instance.
Hope it helps!

Is this a proper use of static methods [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have read so many conflicting opinions on the use of static methods that my head hurts. Consider the following:
In most of my CRUD applications I use a SqlDataHandler class to handle the interactions with the database for a class (or in some cases group of classes). See below:
public abstract SqlDataHandler
{
#region Properties
protected static string ConnectionString { get; set; }
#endregion
#region Methods
protected static DataTable GetDataTable(SqlCommand GetTableCommand)
{
...
}
#endregion
}
public AccountSqlDataHandler : SqlDataHandler
{
#region Methods
public static DataTable GetAccountHistory()
{
SqlCommand getAccountHistoryCommand;
...
return AccountSqlDataHandler.GetDataTable(getAccountHistoryCommand);
}
#endregion
#region Ctors
static AccountSqlDataHandler()
{
AccountSqlDataHandler.ConnectionString = "Connection string for account database";
}
#endregion
}
public Account
{
#region Properties
public List<HistoryItem> AccountHistory
{
get
{
List<HistoryItem> accountHistory;
accountHistory =
this.getItemsFromDataTable(AccountSqlDataHandler.GetAccountHistory());
return accountHistory;
}
}
#endregion
}
As I see it if I use member methods, then either I have to create an AccountSqlDataHandler instance each time, or create an AccountSqlDataHandler member in the Account class. I don't see any advantage to doing this, but from what I'm reading there is an advantage. I would like to understand what it is before I blindly change my methodology.
A good rule of thumb is to use a static method if the method is not dependent on a specific instance. I.E.
public static int Add (x, y)
{
return x + y;
}
And you should use instance methods if you do depend on the instance.
public int Add(x)
{
return this.y + x;
}
Now your specific issue is Maybe you connect to multiple databases, or you have multiple connection strings.
If you do, than it makes perfect sense to instantiate your sql data handlers. but if you don't than there's not much need.
Nope. In fact, there will be a nice bug for you when you add and use a second handler.
Try this code out (hopefully you'll notice the similarity with your ConnectionString property):
internal class Program
{
private static void Main(string[] args)
{
var bravo = new Bravo();
var charlie = new Charlie();
Console.WriteLine(bravo.GetValue());
Console.WriteLine(charlie.GetValue());
Bravo.EchoValue();
Charlie.EchoValue();
}
}
public abstract class Alpha
{
protected static string Value { get; set; }
public abstract string GetValue();
}
public class Bravo : Alpha
{
static Bravo()
{
Value = "bravo";
}
public override string GetValue()
{
return Value;
}
public static void EchoValue()
{
Console.WriteLine(Value);
}
}
public class Charlie : Alpha
{
static Charlie()
{
Value = "charlie";
}
public override string GetValue()
{
return Value;
}
public static void EchoValue()
{
Console.WriteLine(Value);
}
}
Output:
charlie
charlie
charlie
charlie
Press any key to continue . . .
ConnectionString is effectively shared state and modifying it in static constructors means that the last static constructor call will set the state for the entire application (until something sets it to what it wants it to be but then this must be the rule and then the static constructors are pointless). This will inevitably lead to the why is my accounts query hitting the orders database? problems (because a developer didn't explicitly set the connection string prior to every usage) as well as kill any chance at this application working in a multi-database context.
In general static should be something when that behavior logically belongs to a class or type instead of its instances and static data when that data is shared among all instances.
In your case it looks like you want a Singleton for each database. Take a look at that pattern. Many times I've seen singleton being implemented as static classes/methods which is not correct.
Another thing in .NET, there is a general guideline that static methods are (should be) thread safe but instance methods are not. You have to take care of this guideline when implementing static methods.

Getter and Setter in generic interface - is this possible?

Still learning my ways around C# generics... is it possible to achieve this functionality?
public interface ISetting<T>
{
void SetSettings(T obj);
// myTypeHere GetSettings(T obj);
}
public class RadDockSetting : ISetting<CormantRadDock>
{
public RadDockSetting()
{
}
public RadDockSetting GetSettings(CormantRadDock dock)
{
}
public void SetSettings(CormantRadDock dock)
{
}
}
I realize this is a counter-intuitive way to be using a Getter -- shouldn't have to pass anything to it. What I'm doing is creating an object, RadDockSetting, that stores the relevant properties of the CormantRadDock -- and then returns the 'got' settings.
GetSettings is currently a static method, but I realize this will need to be refactored in order to allow implementing a getter from the interface. Maybe once this occurs the 'weirdness' of the getter will fall away?
So, a little background on all of this:
I started with a class that had a lot of 'copy/pasted' functions. These functions were in charge of saving and removing controls from a manager. When I realized this I set out trying to make these functions more generic. I succeeded, with SO's help, in making remove generic.
For reference, here is remove:
public static void Remove<T>(string controlID) where T: new()
{
Logger.InfoFormat("Removing control {0}", controlID);
T states = RadControlStates.GetStates<T>();
(states as IDictionary).Remove(controlID);
RadControlStates.SetStates<T>(states);
}
and it is called like so: RadControlSave.Remove<SerializableDictionary<string, RadPaneSetting>>(ID);
Now, I am trying to extend this genericness to the rest of the methods -- the savers. Here's how one of these methods looks currently:
public static void SavePane(CormantRadPane pane)
{
Logger.InfoFormat("Saving pane {0}", pane.ID);
RadPaneSetting paneSettings = RadPaneSetting.GetSettings(pane);
SerializableDictionary<string, RadPaneSetting> paneStates = RadControlStates.GetStates<SerializableDictionary<string, RadPaneSetting>>();
bool paneIsKnown = paneStates.ContainsKey(paneSettings.ID);
if (paneIsKnown)
{
Logger.Debug("Pane is known. Overwriting data.");
paneStates[paneSettings.ID] = paneSettings;
}
else
{
Logger.Debug("Pane is unknown. Saving data.");
paneStates.Add(paneSettings.ID, paneSettings);
}
RadControlStates.SetStates<SerializableDictionary<string, RadPaneSetting>>(paneStates);
}
At the start of this code block there is a call to "RadPaneSetting.GetSettings(pane)".
RadPaneSettings implements the ISettings interface. Here is ISetting's setter being used.
/// <summary>
/// Recreates a dashboard control based off of its settings.
/// </summary>
/// <typeparam name="T"> The type of control to be recreated. </typeparam>
/// <param name="settings"> The known settings needed to recreate the control.</param>
/// <returns> The recreated control. </returns>
public static T Recreate<T>(ISetting<T> settings) where T : new()
{
T _control = new T();
settings.SetSettings(_control);
Logger.DebugFormat("Recreated control {0}", (_control as Control).ID);
return _control;
}
It looks like you just need to add another generic parameter here
public interface ISetting<T1, T2>
{
void SetSettings(T1 obj);
T2 GetSettings(T1 obj);
}
public class RadDockSettings : ISetting<CormantRadDock, RadDockSetting>
Your question is not very clear but do you need a property:
public interface ISetting<T>
{
T Setting { get; set; }
}
public class RadDockSetting : ISetting<CormantRadDock>
{
public CormantRadDock Setting { get; set; }
}
What you have would work if you define another generic parameter (as #jaredPar pointed out). You may want to consider using Extension Methods rather than the class approach, though. It would allow you to have a "cleaner" API for getting the settings.
Sample:
public static class RadDockExtensions
{
public static RadDockSetting GetSettings(this CormantRadDock dock)
{
// Implementation
}
}
Or if you want something more generic
public static class RadDockExtensions
{
public static U GetSettings<T,U>(this T dock)
{
// Implementation
}
}
Though in this case you would need to add some constraints to actually create the implementation
It's not entirely clear to me what the purpose of the SetSettings method is, since you appear to be sending in the same object your sending to GetSettings.
In both cases you would use the above code like this:
RadDockSetting mySettings = myDock.GetSettings();
hmmmm might have missed the point.
but why would a settings class have a getSettings call? would it just return this?
The set takes a dock to initialise the instance, then get is merely the instance.
I'm not really sure what you want to do.
Maybe an extension method could do the trick rather than a method inside the interface ISetting... something like that :
public static T GetSettings<T,C>(this T t, C c) where T : ISetting<C>
{
return t;
}
Hope this helps...

What's wrong with this singleton I created

I created a class which allows access to global access to a variable while only creating it once, essentially a singleton.
However, it doesn't match any of the 'correct' ways to implement a singleton. I assume that it's not mentioned because there is something 'wrong' with it but I can't see any problem with it other then the lack of lazy initialization.
Any thoughts?
static class DefaultFields
{
private static readonly string IniPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "defaultFields.ini");
private static readonly IniConfigSource Ini = GetIni();
/// <summary>
/// Creates a reference to the ini file on startup
/// </summary>
private static IniConfigSource GetIni()
{
// Create Ini File if it does not exist
if (!File.Exists(IniPath))
{
using (FileStream stream = new FileStream(IniPath, FileMode.CreateNew))
{
var iniConfig = new IniConfigSource(stream);
iniConfig.AddConfig("default");
iniConfig.Save(IniPath);
}
}
var source = new IniConfigSource(IniPath);
return source;
}
public static IConfig Get()
{
return Ini.Configs["default"];
}
public static void Remove(string key)
{
Get().Remove(key);
Ini.Save();
}
public static void Set(string key, string value)
{
Get().Set(key, value ?? "");
Ini.Save();
}
}
It doesn't follow the usual singleton patterns as your class is static and just controls access to static variables.
Where as a singleton is normally a static single instance of a class where the only static functions are that to create and access the singleton that stores variables as normal non static member variables.
Meaning the class could quite easily be changed or made to be instanced more then once but yours cannot
You are right about the singleton, its a class with a unique instance that provides global access.
It might seem like a static class but usually its implemented in a different way.
Also bear in mind that this pattern should be used with some precaution, as its really hard to refactor out a singleton once its deep in the code. Should be used primarily when you have hardware constraints or are implemented unique points of access to a factory. I would try to avoid it whenever possible.
An example of an implementation is as follows:
public class A
{
/// <summary>
/// Unique instance to access to object A
/// </summary>
public static readonly A Singleton = new A();
/// <summary>
/// private constructor so it can only be created internally.
/// </summary>
private A()
{
}
/// <summary>
/// Instance method B does B..
/// </summary>
public void B()
{
}
}
And could be used like
A.Singleton.B()
Hope that helps.
All the methods on your class are static, so you are hiding the single instance from your users. With the singleton pattern the single instance is exposed via a public property usually called Instance (in other languages like Java it might be a method called getInstance or similar).
Your code is not wrong - it's just not the singleton pattern. If you wish to implement a singleton I would recommend Jon Skeet's article Implementing the Singleton Pattern in C#.
The biggest problem I see is that you're not doing any SyncLock-ing around writes to your INI file - multiple threads that attempt to write values at the same time could end up with unpredictable results, like both making writes and only one persisting (or multiple threads attempting to write the file at once, resulting in an IO error).
I'd create a private "Locking" object of some kind and then wrap the writes to your file in a SyncLock to ensure that only one thread at a time has the ability to change values (or, at the very least, commit changes to the INI file).
I am interested in answers to this question as well. In my opinion, there is a flood of singleton examples that use lazy instantiation, but I think you have to ask yourself if it's really necessary on a case by case basis.
Although this article pertains to Java, the concepts should still apply. This provides a number of examples for different singleton implementations. http://www.shaunabram.com/singleton-implementations/
I've also seen numerous references to the book "Effective Java", Item 71 - use lazy instantiation judiciously. Basically, don't do it unless you need to.
That's not really a singleton, it's a static class.
In many ways, static classes are similar to singleton's, true. But static classes can't implement interfaces, can't inherit functionality from a base class, and you can't carry a reference to them.
Why the readonly on the Ini field?
But if you want implement the singleton pattern, it's something like this:
static DefaultFields
{
private readonly string IniPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "defaultFields.ini");
private readonly IniConfigSource Ini = GetIni();
private static DefaultFields _default;
public static DefaultFields Default
{
get { if(this._default == null){ this._default = new DefaultFields(); } return this._default; }
}
private DefaultFields()
{
}
/// <summary>
/// Creates a reference to the ini file on startup
/// </summary>
private IniConfigSource GetIni()
{
// Create Ini File if it does not exist
if (!File.Exists(IniPath))
{
using (FileStream stream = new FileStream(IniPath, FileMode.CreateNew))
{
var iniConfig = new IniConfigSource(stream);
iniConfig.AddConfig("default");
iniConfig.Save(IniPath);
}
}
var source = new IniConfigSource(IniPath);
return source;
}
public IConfig Get()
{
return Ini.Configs["default"];
}
public void Remove(string key)
{
Get().Remove(key);
Ini.Save();
}
public void Set(string key, string value)
{
Get().Set(key, value ?? "");
Ini.Save();
}
}
lazy initialization is very important for a singleton class. By declaring your class to be static you implement a static class, not a singleton class.

How to implement a singleton in C#?

How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create.
If you are just storing some global values and have some methods that don't need state, you don't need singleton. Just make the class and its properties/methods static.
public static class GlobalSomething
{
public static int NumberOfSomething { get; set; }
public static string MangleString( string someValue )
{
}
}
Singleton is most useful when you have a normal class with state, but you only want one of them. The links that others have provided should be useful in exploring the Singleton pattern.
Singletons only make sense if both of these conditions are true:
The object must be global
There must only ever exist a single instance of the object
Note that #2 does not mean that you'd like the object to only have a single instance - if thats the case, simply instantiate it only once - it means that there must (as in, it's dangerous for this not to be true) only ever be a single instance.
If you want global, just make a global instance of some (non signleton) object (or make it static or whatever).
If you want only one instance, again, static is your friend. Also, simply instantiate only one object.
Thats my opinion anyway.
Singleton != Global. You seem to be looking for the keyword static.
You can really simplify a singleton implementation, this is what I use:
internal FooService() { }
static FooService() { }
private static readonly FooService _instance = new FooService();
public static FooService Instance
{
get { return _instance; }
}
Hmm, this all seems a bit complex.
Why do you need a dependency injection framework to get a singleton? Using an IOC container is fine for some enterprise app (as long as it's not overused, of course), but, ah, the fella just wants to know about implementing the pattern.
Why not always eagerly instantiate, then provide a method that returns the static, most of the code written above then goes away. Follow the old C2 adage - DoTheSimplestThingThatCouldPossiblyWork...
I would recommend you read the article Exploring the Singleton Design Pattern available on MSDN. It details the features of the framework which make the pattern simple to implement.
As an aside, I'd check out the related reading on SO regarding Singletons.
Ignoring the issue of whether or not you should be using the Singleton pattern, which has been discussed elsewhere, I would implement a singleton like this:
/// <summary>
/// Thread-safe singleton implementation
/// </summary>
public sealed class MySingleton {
private static volatile MySingleton instance = null;
private static object syncRoot = new object();
/// <summary>
/// The instance of the singleton
/// safe for multithreading
/// </summary>
public static MySingleton Instance {
get {
// only create a new instance if one doesn't already exist.
if (instance == null) {
// use this lock to ensure that only one thread can access
// this block of code at once.
lock (syncRoot) {
if (instance == null) {
instance = new MySingleton();
}
}
}
// return instance where it was just created or already existed.
return instance;
}
}
/// <summary>
/// This constructor must be kept private
/// only access the singleton through the static Instance property
/// </summary>
private MySingleton() {
}
}
Static singleton is pretty much an anti pattern if you want a loosely coupled design. Avoid if possible, and unless this is a very simple system I would recommend having a look at one of the many dependency injection frameworks available, such as http://ninject.org/ or http://code.google.com/p/autofac/.
To register / consume a type configured as a singleton in autofac you would do something like the following:
var builder = new ContainerBuilder()
builder.Register(typeof(Dependency)).SingletonScoped()
builder.Register(c => new RequiresDependency(c.Resolve<Dependency>()))
var container = builder.Build();
var configured = container.Resolve<RequiresDependency>();
The accepted answer is a terrible solution by the way, at least check the chaps who actually implemented the pattern.
public class Globals
{
private string setting1;
private string setting2;
#region Singleton Pattern Implementation
private class SingletonCreator
{
internal static readonly Globals uniqueInstance = new Globals();
static SingletonCreator()
{
}
}
/// <summary>Private Constructor for Singleton Pattern Implementaion</summary>
/// <remarks>can be used for initializing member variables</remarks>
private Globals()
{
}
/// <summary>Returns a reference to the unique instance of Globals class</summary>
/// <remarks>used for getting a reference of Globals class</remarks>
public static Globals GetInstance
{
get { return SingletonCreator.uniqueInstance; }
}
#endregion
public string Setting1
{
get { return this.setting1; }
set { this.setting1 = value; }
}
public string Setting2
{
get { return this.setting2; }
set { this.setting2 = value; }
}
public static int Constant1
{
get { reutrn 100; }
}
public static int Constat2
{
get { return 200; }
}
public static DateTime SqlMinDate
{
get { return new DateTime(1900, 1, 1, 0, 0, 0); }
}
}
I like this pattern, although it doesn't prevent someone from creating a non-singleton instance. It can sometimes can be better to educate the developers in your team on using the right methodology vs. going to heroic lengths to prevent some knucklehead from using your code the wrong way...
public class GenericSingleton<T> where T : new()
{
private static T ms_StaticInstance = new T();
public T Build()
{
return ms_StaticInstance;
}
}
...
GenericSingleton<SimpleType> builder1 = new GenericSingleton<SimpleType>();
SimpleType simple = builder1.Build();
This will give you a single instance (instantiated the right way) and will effectively be lazy, because the static constructor doesn't get called until Build() is called.
What you are describing is merely static functions and constants, not a singleton. The singleton design pattern (which is very rarely needed) describes a class that is instantiated, but only once, automatically, when first used.
It combines lazy initialization with a check to prevent multiple instantiation. It's only really useful for classes that wrap some concept that is physically singular, such as a wrapper around a hardware device.
Static constants and functions are just that: code that doesn't need an instance at all.
Ask yourself this: "Will this class break if there is more than one instance of it?" If the answer is no, you don't need a singleton.
hmmm... Few constants with related functions... would that not better be achieved through enums ? I know you can create a custom enum in Java with methods and all, the same should be attainable in C#, if not directly supported then can be done with simple class singleton with private constructor.
If your constants are semantically related you should considered enums (or equivalent concept) you will gain all advantages of the const static variables + you will be able to use to your advantage the type checking of the compiler.
My 2 cent
Personally I would go for a dependency injection framework, like Unity, all of them are able to configure singleton items in the container and would improve coupling by moving from a class dependency to interface dependency.
You can make a simple manual static singleton implementation for your common (non-static) class by adding a static property Instance (name can vary) into it with initialization like this:
public class MyClass
{
private static MyClass _instance;
public static MyClass Instance => _instance ?? (_instance = new MyClass());
// add here whatever constructor and other logic you like or need.
}
Then it can be resolved anywhere from this namespace like this:
var myClass = MyClass.Instance; // without any new keyword
myClass.SomeNonStaticMethod();
// or:
MyClass.Instance.SomeNonStaticMethod();
// or:
MyClass.Instance.SomeNonStaticProperty = "new value";
By hiding public constructor, adding a private static field to hold this only instance, and adding a static factory method (with lazy initializer) to return that single instance
public class MySingleton
{
private static MySingleton sngltn;
private static object locker;
private MySingleton() {} // Hides parameterless ctor, inhibits use of new()
public static MySingleton GetMySingleton()
{
lock(locker)
return sngltn?? new MySingleton();
}
}
I have written a class for my project using Singleton pattern. It is very easy to use. Hope it will work for you. Please find the code following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TEClaim.Models
{
public class LogedinUserDetails
{
public string UserID { get; set; }
public string UserRole { get; set; }
public string UserSupervisor { get; set; }
public LogedinUserDetails()
{
}
public static LogedinUserDetails Singleton()
{
LogedinUserDetails oSingleton;
if (null == System.Web.HttpContext.Current.Session["LogedinUserDetails"])
{
oSingleton = new LogedinUserDetails();
System.Web.HttpContext.Current.Session["LogedinUserDetails"] = oSingleton;
}
else
{
oSingleton = (LogedinUserDetails)System.Web.HttpContext.Current.Session["LogedinUserDetails"];
}
//Return the single instance of this class that was stored in the session
return oSingleton;
}
}
}
Now you can set variable value for the above code in your application like this..
[HttpPost]
public ActionResult Login(FormCollection collection)
{
LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
User_Details.UserID = "12";
User_Details.UserRole = "SuperAdmin";
User_Details.UserSupervisor = "815978";
return RedirectToAction("Dashboard", "Home");
}
And you can retrieve those value like this..
public ActionResult Dashboard()
{
LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
ViewData["UserID"] = User_Details.UserID;
ViewData["UserRole"] = User_Details.UserRole;
ViewData["UserSupervisor"] = User_Details.UserSupervisor;
return View();
}
In c# it could be (Thread safe as well as lazy initialization):
public sealed class MySingleton
{
static volatile Lazy<MySingleton> _instance = new Lazy<MySingleton>(() => new MySingleton(), true);
public static MySingleton Instance => _instance.Value;
private MySingleton() { }
}

Categories