Moving singleton definition into mixins in C# - c#

I have to change around 10 classes into singletons and I thought that instead of copy-pasting the code it makes sense to use mixins, like it is described here: http://msdn.microsoft.com/en-us/vstudio/bb625996.aspx
However, I need not that much of additional methods, but more additional changes to the class itself, I have problems applying those instructions.
I tried to create an empty interface ISingleton and then to add the singleton part as extension to the new class public static class Singleton
This is singleton part which I would like to use:
public static SomeClass Instance
{
get { return _instance ?? (_instance = new SomeClass ()); }
}
private static SomeClass _instance;
But when adding it as extension I had a problem - how to define the Instance property, so it will be reusable by many classes?
And the second issue - I still need to change the constructors to private manually.
Does this approach makes any sense?
I haven't used mixins before, maybe this is just not the right scenario for it?

The mixins link you gave shows extension methods being used to add functionality to all objects supporting an interface. You still need to create the objects first. As singleton patterns handle the creation of objects it's basicly too soon to apply these techiniques.
Singleton needn't be so complicated, you're reading Jon Skeets article, a simple:
public sealed MyClass
{
private MyClass(){}
public static MyClass Instance = new MyClass();
}
Is often all you need. I'd happily repeat that code 10 times if needed. Or one can use a service locator or IoC container to manage the lifetime of objects.

Related

What's the difference between these two singleton class structures?

I'm wondering what the differences are between these two singleton classes. My professor showed us the last one said it was more flexible and better in it's performance. I'm also wondering why my professors version has a private constructor, can someone clearify why that is?
Version 1 - my version (standard I believe):
public class Singleton {
public static Singleton GetInstance() {
return Singleton.instance ?? (Singleton.instance = new Singleton());
}
Version 2 - flexible and high-performance:
public class Singleton {
private Singleton() {} // Why this?
private static class SingletonHolder() {
public static readonly Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
In c#, Private Constructor is a special instance constructor and it is used in a classes that contains only static members. If a class contains one or more private constructors and no public constructors, then the other classes are not allowed to create an instance for that particular class except nested classes.
constructor is private, Because we don't want any outer class create an instance of this class.
and about performance, in version 1 you have to check: if instance of class is empty then create an instance, But in version 2 you have a static constructor with a readonly field, that mean the instance will be initialized when class call for the first time and for the next call static constructor never called again.
For more explanation about singleton pattern, you can follow this link
The constructor is private to prevent others from instantiating the class explicitly, thereby strictly enforcing the singleton pattern.
As for the nested class, it makes it lazy and thread-safe without requiring locks. Flexibility and High-Performance are semantics on top of those primary benefits. (I mean, if you really want high performance you should be coding C or C++, for real). Jon Skeet explains it here. https://csharpindepth.com/articles/Singleton (Fifth version)
In this day and age, Version 1 isn't exactly standard, most of the libraries use the System.Lazy<T> wrapper which manages lazyness without the boilerplate of nested classes.

Initializing Singleton Instance Inside Static Constructor

I want to implement simple Singleton and after some investigation have following to working fine. I test it using a simple console app but will be helpful if someone else can comment on it. The reason I've a doubt because new instance of Singleton is created within a static constructor and not sure if that's has any side effects.
sealed class SingletonEx
{
public static readonly SingletonEx Instance;
static SingletonEx()
{
if (null == Instance)
{
Instance = new SingletonEx();
}
}
private SingletonEx() { }
}
In case you're curious I found http://csharpindepth.com/Articles/General/Singleton.aspx quite helpful on this topic.
This is not a typical usage for static constructor, although it is possible to do so. Side effect would be that constructor would run before first using of any SingletonEx instance will be used in your code. Having a static constructor wouldn't change much about the "Singleton" behaviour. But, pay attention that initilization would happend in another stage than it would usually be if it wern't static.
I'd be worried for the following line:
public static readonly SingletonEx Instance;
Here are your problems:
public - Means it could be changed outside of the class.Because the Singleton instance is referenced by a private static member variable, the instantiation does not occur until the class is first referenced by a call to the Instance property. This solution therefore implements a form of the lazy instantiation property, as in the Design Patterns form of Singleton. When implement design pattern follow as much as you can on it's design.
readonly - shouldn't be here either. It is usually editable, unless you have a good reason for that.

Coding practice - using abstract or a private constructor

I have a question about coding practice. I want to create a class which can't be initialized. I believe I have 3 options:
Abstract modifier
Static modifier
Private constructor
I don't want to create a static class simply because of having to name all of my properties and methods 'static' - it looks messy (and I can't use the 'this' keyword).
According to the MSDN:
Use the abstract modifier in a class declaration to indicate that a
class is intended only to be a base class of other classes.
Edit Nothing will inherit form this class.
However, it would be a solution (but it seems wrong to me to use it in this situation).
Or, I can make a private constructor so the class cannot be initialized.
If it helps the reason for why is this: The class is responsible for starting off a work flow process. It doesn't need to be initialized since nothing is returned - it just needs to be 'started'.
Demo code
class Program
{
static void Main(string[] args)
{
WorkFlow wf = new WorkFlow(); // this will error which is fine!
ComplexObject co = new ComplexObject();
WorkFlow.Begin(co);
Console.ReadKey();
}
}
public class WorkFlow
{
private WorkFlow()
{
//private to prevent initialization but this feels wrong!
}
public static void Begin(ComplexObject co)
{
//code to begin the workflow
}
}
I want to create a class which can't be initialized.
That leaves the possible usages: static or base-class only.
If your class is going to be derived from, use abstract. A private/protected constructor would be a hack in this situation.
Your sample code looks more like a static class. With Singleton as alternative.
What about doing just what you have done but using your Begin method as a factory to create your workflow.
var workflow = Workflow.Begin(complexObject);
public class WorkFlow
{
private WorkFlow()
{
//private to prevent initialization but this feels wrong!
}
public static WorkFlow Begin(ComplexObject co)
{
return new Workflow(co);
}
}
Good practice: Private constructor (at least is what the GOF book recommends when using the Factory pattern, for example). I'll suggest you to use abstract if it's a base class (that's what it's name suggest).
If the class is strictly being used as a base class, it would have to be abstract for me.
Based on your update I would go for a static class & method e.g.
WorkFlow.Begin(co);
However, since you don't want to do this I think it only leaves you with one option...private constructor.
Seems like you would need a singleton.
More reference here:
http://msdn.microsoft.com/en-us/library/ff650849.aspx
if you dont like the ideea, well an abstract class would be best suited because as you said you dont want to instantiate it, and lets not forget that the abstract class does just that, so why try and use a private constructor.
I don't want to create a static class simply because of having to name
all of my properties and methods 'static' - it looks messy (and I
can't use the 'this' keyword).
Well, either you make ctor private or make a class static, the only way caller can access methods and properties of your class (if the caller is not derived one) is via public static members.
Having private ctor give you more flexibility in inheritance chain, but doesn't help much in "avoid static members" scenario.
I will prefer private constructor ie its identical to Singleton pattern
Info
Coding
Private constructors seems to be good approach for your requirement. Abstracts are good too but private constructor is handy than abstract. But if you would like to extend its information then its probably good idea to use abstract.
If the class needs to be "started" it needs to be initialized (unless all you're going to use are static methods).
Abstract classes are used to leave some (or all) of the implementation to subclasses, and by your description - not suitable for you.
"Static classes" - no special gain here I guess (in your case).
Private constructors - used to limit who can instantiate the class.
Not sure that any of these matches your design, but I guess you really want a singleton - look it up, this is the most common and basic design pattern.
BTW - I use singletons only as a last resort, usually when the class controls some kind of non shared resource.

Best way to prevent a class from being Instantiated?

I need to know how to prevent a class from being Instantiated in .net?
I know few methods like making the class Abstract and Static.
Is there any more way to achieve this?
Making the class static is the best approach, if you absolutely don't want any instances. This stops anyone from creating instances. The class will be both sealed and abstract, and won't have any constructors.
Additionally, the language will notice that it's a static class and stop you from using it in various places which imply instances, e.g. type arguments and variables. This indicates the intention more clearly than just having a private constructor - which could mean that there are instances, created within that class (e.g. for a singleton implementation).
Oh, and making the class static will stop you from introducing any pointless instance members in the class, too :)
See MSDN for more information about static classes.
Mark the constructor(s) private, protected or if in used from another assembly, internal
Marking the constructor private. Of course, this doesn't prevent the class from instantiating itself through a static method, for example...
More practically, what's the purpose of disallowing class instantiation. If it's to have a singleton, then a private constructor is appropriate. If it's to force subclassing, making the class abstract is better; if it's to have a class with utility methods, making it static is one way (then you can only have static methods).
I need to know how to prevent a class from being Instantiated in .net?
Your question is not clear.
Do you mean instantiated at runtime? Make the class abstract or static.
Do you mean that the constructor is not accessible in code? Make the constructor private. But note that someone could still use reflection to grab a handle on a constructor and instantiate an instance at runtime.
So, which do you mean?
If the question is:
How can you make your class not be instanced without having your class
be static or abstract?
Then the answer to this is to implement the singleton pattern, which in .NET 4+ this is done easily with:
public sealed class myClass
{
private static readonly Lazy<myClass> lazyInstance =
new Lazy<myClass>(() => new myClass());
public static Instance
{
get
{
return lazyInstance.Value;
}
}
private myClass()
{
// constructor logic here
}
}
The singleton pattern allows you to pass your class around as a reference to methods, while still ensuring that you have only a single instance of your class. It also makes testing much easier as you can have a ImyClass instance which myClass implements, this is very helpful when making mock objects.
Without .NET4 you can still implement the singleton pattern, for example:
private static readonly myClass instance = new myClass();
public static Instance
{
get
{
return instance;
}
}
// rest of code remains the same
Which doesn't have deferred loading until it's called, there's lots of other ways as well (I think about 6 different ways), but the above two are the most common ones.
In summary the question is likely asking if you know the singleton pattern and if you recognise it's importance over static classes for unit tests and mock objects.
As others have already pointed out, static fields, even those marked readonly can be set with reflection, in addition the private constructor can be called using reflection. If you need to prevent these, either you need to make the calling code run in a less trusted app-domain space, or you will need to implement your class as static.
Generally though, people don't bother with such levels of reflection to get around your constraints unless they 'really need to' for example, writing obscure / extreme fringe case unit tests.

How can I make a class global to the entire application?

I would like to access a class everywhere in my application, how can I do this?
To make it more clear, I have a class somewhere that use some code. I have an other class that use the same code. I do not want to duplicate so I would like to call the same code in both place by using something. In php I would just include("abc.php") in both... I do not want to create the object everytime I want to use the code.
Do you want to access the class or access an instance of the class from everywhere?
You can either make it a static class - public static class MyClass { } - or you can use the Singleton Pattern.
For the singleton pattern in its simplest form you can simply add a static property to the class (or some other class) that returns the same instance of the class like this:
public class MyClass
{
private static MyClass myClass;
public static MyClass MyClass
{
get { return myClass ?? (myClass = new MyClass()); }
}
private MyClass()
{
//private constructor makes it where this class can only be created by itself
}
}
The concept of global classes in C# is really just a simple matter of referencing the appropriate assembly containing the class. Once you have reference the needed assembly, you can refer to the class of choice either by it's fully qualified Type name, or by importing the namespace that contains the class. (Concrete instance or Static access to that class)
Or
You can have a Singleton class to use it everywhere but some people won't recommend you this way to proceed.
The other answers that you've been given about using a static class or a singleton pattern are correct.
Please consider, however, the fact that doing so does compromise your ability to test. In general, if you can, prefer dependency injection over globally accessed classes. I know this isn't always possible (or practical).
Just on that, you should also look up the abstract factory pattern. It allows you to have a well known factory class that produces the actual instance of a class that you're using. To have a globally accessed logging class, for example, don't directly create a logging class. Instead, use a logging factory to create it for you and return an interface to a logging class. That way it's easier to swap in and out different logging classes.
Since you do not want to create the object every time and it sounds like you are talking about some sort of utility methods...
I suggest you use static methods in an assembly which you can reference where needed

Categories

Resources