Force singleton pattern in subclasses - c#

I would like to force subclasses to implement the singleton pattern.
I originally thought of having an abstract static property in the parent class, but upon closer though, that didn't make sense (abstract requires and instance).
Next, I thought of having an interface with a static property, but that also doesn't make sense (interfaces also require an instance).
Is this something which is possible, or should I give up this train of thought and implement an abstract factory?

Please reconsider. You do NOT want to use singletons here. You are making some functionality available to users who derive from your class. That's fine. But you're also dictating one specific way in which it must always be used, and for absolutely no reason. That is not good.
It may make sense to only instantiate one object of this class the majority of the time, but in that case, simply just instantiate the object once. It's not like you're very likely to accidentally instantiate a dozen objects without noticing.
Moreover, how can you tell that having two instances will NEVER be useful? I can think of several cases even now.
Unit testing: You might want each test to instantiate this object, and tear it down again afterwards. And since most people have more than one unit test, you'll need to instantiate it more than once.
Or you might at some point decide to have multiple identical/similar levels in your game, which means creating multiple instances.
A singleton gives you two things:
A guarantee that no more than one instance of the object will ever be instantiated, and
Global access to that instance
If you don't need both these things, there are better alternatives.
You certainly don't need global access. (globals are bad, and usually a symptom of bad design, especially in mutable data such as your game state)
But you don't need a guarantee that no more than one instances will ever be instantiated either.
Is it the end of the world if I instantiate the object twice? Will the application crash? If so, you need that guarantee.
But in your case, nothing bad will happen. The person instantiating the object simply uses more memory than necessary. But he might have a reason.
Simply put in the class documentation that this is a very big and expensive class, and you shouldn't instantiate it more often than necessary. Problem solved. You don't remove flexibility that might turn out to be useful later on, you don't grant global access to data for no reason. Because you can control who can see the object, you don't need to drown it in locks that will become a bottleneck in multithreaded applications. You don't have hidden dependencies scattered throughout your code, making it harder to test and harder to reuse.

Try using an IOC container. Most good IOC containers enable the use of the singleton pattern without having to implement it yourself (ie: spring framework) - I like this better than forcing a static GetInstance() method.
Besides, it's not really possible in java, it would work in C++ with templates though.

Why? If someone wants to use multiple instances of a subclass of your class they might have a perfectly valid reason to.
If you want to do something that only should be done once for each class that subclasses your class (why, I have no idea, but you might have a reason to), use a Dictionary in the base class.

I would define a sealed class that gets its functionality from delegates passed to the constructor, something like this:
public sealed class Shape {
private readonly Func<int> areaFunction;
public Shape(Func<int> areaFunction) { this.areaFunction = areaFunction; }
public int Area { get { return areaFunction(); } }
}
This example does not make a lot of sense, it just illustrates a pattern.
Such a pattern cannot be used everywhere, but sometimes it helps.
Additionally, it can be extended to expose a finite number of static fields:
public sealed class Shape {
private readonly Func<int> areaFunction;
private Shape(Func<int> areaFunction) { this.areaFunction = areaFunction; }
public int Area { get { return areaFunction(); } }
public static readonly Shape Rectangle = new Shape(() => 2 * 3);
public static readonly Shape Circle = new Shape(() => Math.Pi * 3 * 3);
}

I think you will be better off with a factory pattern here to be honest. Or use an IoC tool like Brian Dilley recommends. In the c# world there are loads, here are the most popular : Castle/windsor, StructureMap, Unity, Ninject.
That aside, I thought it would be fun to have a go at actually solving your problem! Have a look at this:
//abstract, no one can create me
public abstract class Room
{
protected static List<Room> createdRooms = new List<Room>();
private static List<Type> createdTypes = new List<Type>();
//bass class ctor will throw an exception if the type is already created
protected Room(Type RoomCreated)
{
//confirm this type has not been created already
if (createdTypes.Exists(x => x == RoomCreated))
throw new Exception("Can't create another type of " + RoomCreated.Name);
createdTypes.Add(RoomCreated);
}
//returns a room if a room of its type is already created
protected static T GetAlreadyCreatedRoom<T>() where T : Room
{
return createdRooms.Find(x => x.GetType() == typeof (T)) as T;
}
}
public class WickedRoom : Room
{
//private ctor, no-one can create me, but me!
private WickedRoom()
: base(typeof(WickedRoom)) //forced to call down to the abstract ctor
{
}
public static WickedRoom GetWickedRoom()
{
WickedRoom result = GetAlreadyCreatedRoom<WickedRoom>();
if (result == null)
{
//create a room, and store
result = new WickedRoom();
createdRooms.Add(result);
}
return result;
}
}
public class NaughtyRoom :Room
{
//allows direct creation but forced to call down anyway
public NaughtyRoom() : base(typeof(NaughtyRoom))
{
}
}
internal class Program
{
private static void Main(string[] args)
{
//Can't do this as wont compile
//WickedRoom room = new WickedRoom();
//have to use the factory method:
WickedRoom room1 = WickedRoom.GetWickedRoom();
WickedRoom room2 = WickedRoom.GetWickedRoom();
//actually the same room
Debug.Assert(room1 == room2);
NaughtyRoom room3 = new NaughtyRoom(); //Allowed, just this once!
NaughtyRoom room4 = new NaughtyRoom(); //exception, can't create another
}
}
WickedRoom is a class that properly implements the system. Any client code will get hold of the singleton WickedRoom class. NaughtyRoom does not implement the system properly, but even this class can't be instantiated twice. A 2nd instantiation results in an exception.

Although this will not enforce the user to have a singleton subclass, you can enforce the user to create only one instance of the class (or its sub-classes) as below. This will throw error if a second instance of any subclass is created.
public abstract class SuperClass {
private static SuperClass superClassInst = null;
public SuperClass () {
if(superClassInst == null) {
superClassInst = this;
}
else {
throw new Error("You can only create one instance of this SuperClass or its sub-classes");
}
}
public final static SuperClass getInstance() {
return superClassInst;
}
public abstract int Method1();
public abstract void Method2();
}

Related

Calling a common method across multiple static classes?

A Quick Note
The code in this post is built on top of a in-house built DirectX-11 engine which means it follows the strict pattern of:
Initialize
while (Running) {
Update
Render
}
However, do not let this deter you as the problem is not related to the DirectX code but instead static classes and methods.
Overview
I have a class called RenderObject which contains a method called Initialize. This method is responsible for building the object's mesh, assigning textures, shaders, and more.
public class RenderObject {
public virtual void Initialize() { }
}
I also have a few static classes that hold reusable assets such as common textures, shaders, models, and meshes. This way I don't have to reload them later. All of these static classes also contain a method called Initialize which is responsible for creating these reusable assets. For this question I will limit this to just the Textures class.
public static class Textures {
public static Texture2D Dirt { get; private set; }
public static Texture2D Grass { get; private set; }
public static void Initialize() {
Dirt = new Texture2D(...);
Grass = new Texture2D(...);
}
}
Finally, I have a class called LoadingSystem which is responsible for loading reusable assets and initializing objects. I initialize this class inside of the Initialize method of my engine, and then call the class' Update method in the Update method of the engine respectively. The LoadingSystem's Update method is responsible for loading and initializing objects using a Queue which is useful for supplying smooth visual feedback.
public class LoadingSystem {
public bool Loading { get; private set; } = true;
private Queue<RenderObject> objectsToRender;
public void AddForLoad(RenderObject obj) => objectsToRender.Enqueue(obj);
public void Update() {
if (objectsToRender.Count > 0) {
RenderObject obj = objectsToLoad.Dequeue();
obj.Initialize();
} else Loading = false;
}
}
The Problem
I would like to call the method Initialize on these static classes with the same process used for the RenderObject queue. Currently I'm forced to do:
CurrentMessage = "Loading Textures";
Render();
Present();
Textures.Initialize();
Progress = ++objectsLoaded / objectsToLoad;
CurrentMessage = "Loading Shaders";
Render();
Present();
Shaders.Initialize();
Progress = ++objectsLoaded / objectsToLoad;
CurrentMessage = "Loading Models";
Render();
Present();
Models.Initialize();
Progress = ++objectsLoaded / objectsToLoad;
I've slimmed it down to a method that handles the repetitive setting of the message, and calls to Render and Present but this is still tedious and it should go through the Update method once per object to remain consistent with the rest of the code.
My Thoughts
I understand that a static class cannot inherit from a class or implement an interface so I am wondering if there is a way to provide a static class and call its Initialize method in a similar manner; even if this means creating a separate method to accomplish it.
I have currently considered two options:
Load static classes individually.
Convert static classes to instance classes and call them with the queue.
The problem with the first option is that I have 12 static classes and would have to update progress and feedback messages, raise events, and re-render the scene for each one.
The problem with the second option is that these static classes only contain static properties and thus by definition should be static as there is no need to ever inherit from them or create an instance of them.
The Question
Is there a way to call a common method across multiple static classes?
Perhaps a way to call the method if it exists with generic types like object or T?
Perhaps the dynamic type may work (though you can't create an instance of static classes)?
I have currently considered two options:
Load static classes individually.
Convert static classes to instance classes and call them with the queue.
A third compromise approach relates to your second idea above, but uses a design pattern known as the Singleton Pattern. Like static classes, there can only be one of them in your process and everyone gets that same thing, however unlike static classes, Singletons can implement interfaces or even descend from other classes.
For this example, I will use the interface approach.
public interface IInitializable
{
void Initialize();
}
All the interface does is to enforce that its implementer has an Initialize method.
My next step is to create a Singleton class. There are a couple of rules to implement the Singleton pattern. Your class must be sealed. Its constructor must be private. It must have a static method or property to return the single instance. That method/property must be threadsafe.
I have used Lazy to do the heavy lifting for me
public sealed class Foo : IInitializable
{
public void Initialize()
{
// Initialize my foo
}
private Foo()
{
}
private static Lazy<Foo> fooLazy = new Lazy<Foo>(() => new Foo());
public static Foo Instance => fooLazy.Value;
}
There are some minor differences to what you were doing with static classes. If Foo was a static class, you would call Foo.Initialize(); As it is Singleton, you would call Foo.Instance.Initialize();
Any other methods or properties would most likely be non-static.
Pulling it all together, you could write code like this. Your queue does not need to know about the classes it holds. You don't actually care. You only want to know that it has the Initialize() method
public class YourClass
{
private Queue<IInitializable> objectsToLoad = new Queue<IInitializable>();
public void Enqueue(IInitializable obj)
{
this.objectsToLoad.Enqueue(obj);
}
public void LoadOrUpdate()
{
// Update Method
if (objectsToLoad.Count > 0)
{
IInitializable obj = objectsToLoad.Dequeue();
obj.Initialize();
}
else
{
// Loading complete.
}
}
}
This class could then be used like this
YourClass yourClass = new YourClass();
yourClass.Enqueue(Foo.Instance);
yourClass.LoadOrUpdate();
Though I hope there is a much better and more detailed answer than this; I've come up with a basic solution. I created a separate Queue<Type> where I add the static classes. I then call their Initialize method with the following:
Type t = typesToInit.Dequeue();
t.GetMethod("Initialize").Invoke(null, new object[] { 0 });
This works well and is rather clean, but I can't help but wonder if there is a better way to do this?

Prevent a subclass of a singleton class from calling the singleton's constructor

Ok, I have a singleton class GraphMaster which contains a number of system-wide values. I have a subclass GraphObject : GraphMaster which has graph specific data. By subclassing, I can access members of either the global class or subclass. And by using a singleton class, I can change the global variables anywhere and have them be reflected in all the subclasses.
However, I'm getting stuck because the base class's constructor wants to call the singleton class's constructor, but it can't as it's marked private.
how do I get around this? Is what I'm trying to do possible? I went down this path due to responses to this post: Can I make a "global" object to store variables for multiple objects?
For example,
public class GraphMasterObject {
private static GraphMasterObject instance;
private GraphMasterObject() { }
}
public static GraphMasterObject Instance {
get {
if (instance == null) instance = new GraphMasterObject();
return instance;
}
}
public int globalVar=10;
}
public class GraphObject : GraphMasterObject {
public GraphObject() {
}
public int localVar=20;
}
I want to be able to do
GraphObject go = new GraphObject();
go.globalVar <- this is 10
GraphMasterObject.Instance.globalVar = 20;
go.globalVar <- now this is 20
Ok, I have a singleton class GraphMaster which contains a number of system-wide values. I have a subclass GraphObject : GraphMaster which has graph specific data.
That's a problem to start with. As soon as you have a class which has subclasses, that it by definition not a singleton. Someone can add another subclass at any point, and even if you only have one instance of each subclass, you'll have two distinct instances which are compatible with the base class.
You could add something in the base class constructor to throw an exception if there's already an instance, but it would be pretty smelly. Fundamentally, singletons are incompatible with subclassing. Rethink your design. (Ideally, avoid the singleton pattern in the first place, but that's another matter...)

Sharing an instantiated class among multiple objects in C#

I currently have a class which I instantiate when I start my program. The class itself will create a new thread and begin to search for broadcasts from routers.
I have other windows, other then MainWindow, which needs to be able to access the data stored within the instance of this class. However, I'm not sure as to how the other windows can reference this data.
Is there some other way I can store the instance of this class so that it is accessible application wide? I need it to start right when the rest of the application starts, so it seemed logical (to me) to have the class be instantiated in the first window.
namespace Lalu_WPF
{
public partial class MainWindow : Window
{
// data storage for program
public FindRouter finder = new FindRouter();
public MainWindow()
{
......
Don't make Singleton (notice the capital letter). It is error prone in multiple threads environments(muttable Singletons) and bad for testing.
What are your requirements?
Do you have to have one object in one application or one object in whole CLR?
I bet the first one.
Make an object in your App class (App.xaml.cs) and then acces it via getter
App MyApplication = ((App)Application.Current);
MyApplication.Router;
Don't use a Singleton, it makes unit testing hard and your code surprising.
Give classes which need access to an instance the instance. That means that every class which needs this single instance should accept either by a constructor argument or setter. Whoever creates the class is then in charge of supplying the dependency. This is called Dependency Injection.
You could make the class a singleton and this way you could access this same instance across the entire application. You can see an example on the msdn website here
Do you have a Program class? In the Windows Forms projects that I do, variables such as that go in Program public static readonly members or in public static properties with get only.
What you're talking about sounds like the Singleton design pattern. You could create a singleton object, a static class, or (what I like) a Monostate object (an object that encapsulates the static class or single instance) , something like this:
public class SingletonWidget
{
private static readonly Implementation SingleInstance ;
public void DoSomething( int someValue )
{
SingleInstance.DoSomething( someValue ) ;
return ;
}
public int SomeProperty
{
get
{
return SingleInstance.SomeProperty ;
}
set
{
SingleInstance.SomeProperty = value ;
}
}
static SingletonWidget()
{
SingleInstance = new Implementation() ;
return ;
}
private class Implementation
{
public void DoSomething( int someValue )
{
// ...
}
public int SomeProperty { get ; private set ; }
}
}
Usage looks like normal object instantation:
SingletonWidget foo = new SingletonWidget() ;
foo.DoSomething(3) ;
but under the covers, there's just a single instance hanging around. Changing from a static class or singleton is trivial as only the wrapper needs to change. Building stubs or mocks is pretty easy, too.
It makes it easy to
Try a DI framework or some less complex implementation of a service locator. That will allow you to provide the instance where it is needed throughout your app without hardcoding in a singleton, which is then painful to write tests around.
I know that Ninject at least provides support for single instances application-wide. I haven't used it in a WPF application but I can't see why not.
As a basic example of a service locator you could do something like the following. I've called the shared class Foo:
public interface IFoo { ... }
public class Foo { ... }
public class ServiceLocator
{
IFoo _foo = new Foo();
public IFoo GetFoo() { return _foo; }
}
public class DependsOnFoo
{
public IFoo Foo = ServiceLocator.GetFoo();
...
}
DependsOnFoo.Foo is the shared instance of Foo by default but when writing automated tests you could swap it out with a stub or mock:
var testTarget = new DependsOnFoo();
testTarget.Foo = mockFooImplementation;
// now testTarget isn't bound to the Foo implementation
As far as I understand your question is how to store a reference to your finder rather than how to create it. If this is the case I would suggest using IDictionary Application.Current.Properties property, which is nothing but a collection of application-scope properties. At startup you can create your object and store a reference to it like this:
Application.Current.Properties["finder"] = new FindRouter();
Then, in any place of your program you can access it like
FindRouter finder = (FindRouter)Application.Current.Properties["finder"];
Hope this helps.

class modifier issues in C# with "private" classes

I had a class that had lots of methods:
public class MyClass {
public bool checkConditions() {
return checkCondition1() &&
checkCondition2() &&
checkCondition3();
}
...conditions methods
public void DoProcess() {
FirstPartOfProcess();
SecondPartOfProcess();
ThirdPartOfProcess();
}
...process methods
}
I identified two "vital" work areas, and decided to extract those methods to classes of its own:
public class MyClass {
private readonly MyClassConditions _conditions = new ...;
private readonly MyClassProcessExecution = new ...;
public bool checkConditions() {
return _conditions.checkConditions();
}
public void DoProcess() {
_process.DoProcess();
}
}
In Java, I'd define MyClassConditions and MyClassProcessExecution as package protected, but I can't do that in C#.
How would you go about doing this in C#?
Setting both classes as inner classes of MyClass?
I have 2 options: I either define them inside MyClass, having everything in the same file, which looks confusing and ugly, or I can define MyClass as a partial class, having one file for MyClass, other for MyClassConditions and other for MyClassProcessExecution.
Defining them as internal?
I don't really like that much of the internal modifier, as I don't find these classes add any value at all for the rest of my program/assembly, and I'd like to hide them if possible. It's not like they're gonna be useful/reusable in any other part of the program.
Keep them as public?
I can't see why, but I've let this option here.
Any other?
Name it!
Thanks
Your best bet is probably to use partial classes and put the three clumps of code in separate files adding to the same class. You can then make the conditional and process code private so that only the class itself can access them.
For "Helper" type classes that aren't going to be used outside the current assembly, Internal is the way to go if the methods are going to be used by multiple classes.
For methods that are only going to be used by a single class, I'd just make them private to the class, or use inner classes if it's actually a class that's not used anywhere else. You can also factor out code into static methods if the code doesn't rely on any (non-static) members of your class.
I can
define MyClass as a partial class,
having one file for MyClass, other for
MyClassConditions and other for
MyClassProcessExecution.
Maybe it's my C++ background, but this is my standard approach, though I bundle small helper classes together into a single file.
Thus, on one of my current projects, the Product class is split between Product.cs and ProductPrivate.cs
I'm going for something else - the issue of public / protected / private may not be solved specifically by this, but I think it lends itself much better to maintenance then a lot of nested, internal classes.
Since it sounds like you've got a set of steps in a sequential algorithm, where the execution of one step may or may not be dependent upon the execution of the previous step. This type of sequential step processing can sometimes use the Chain of Responsibility Pattern, although it is morphed a little bit from its original intention. Focussing only on your "processing method", for example, starting from something like below:
class LargeClass
{
public void DoProcess()
{
if (DoProcess1())
{
if (DoProcess2())
{
DoProcess3();
}
}
}
protected bool DoProcess1()
{
...
}
protected bool DoProcess2()
{
...
}
protected bool DoProcess3()
{
...
}
}
Using Chain of Responsibility, this could be decomposed into a set of concrete classes for each step, which inherit from some abstract step class. The abstract step class is more responsible for making sure that the next step is called, if the necessary preconditions are met.
public class AbstractStep
{
public AbstractStep NextStep { get; set; }
public virtual bool ExecuteStep
{
if (NextStep != null)
{
return NextStep.ExecuteStep();
}
}
}
public class ConcreteStep1 : AbstractStep
{
public bool ExecuteStep
{
// execute DoProcess1 stuff
// call base
return base.ExecuteStep();
}
}
...
public class ConcreteStep3 : AbstractStep
{
public bool ExecuteStep
{
// Execute DoProcess3 stuff
// call base
return true; // or false?
}
}
To set this up, you would, in some portion of the code, do the following:
var stepOne = new ConcreteStep1();
var stepTwo = new ConcreteStep2();
var stepThree = new ConcreteStep3();
stepOne.NextStep = stepTwo;
stepTwo.NextStep = stepThree;
bool success = stepOne.ExecuteStep();
This may help clean up the code bloat you've got in your single class - I've used it for a few sequential type algorithms in the past and its helped isolate each step nicely. You could obviously apply the same idea to your condition checking (or build them into each step, if that applies). You can also do some variation on this in terms of passing state between the steps by having the ExecuteStep method take a parameter with a state object of some sort.
Of course, if what you're really concerned about in this post is simply hiding the various steps, then yes, you could make each of your substeps a protected class within your class that creates the steps. Unless you're exposing your library to customers in some form or fashion however, and you don't want them to have any type of visibility into your execution steps, this seems to be a smaller concern then making the code maintainable.
Create the classes with the same access modifier as the methods you have refactored. Partial classes are only really usefull when you have multiple people or automat5ed code generating tools frequently modifying the same classes. They just really avoid source merge hell where your source controll mashes your code because it can't merge multiple edits to the same file.

Nested class with hidden constructor impossible in c#?

I' ve been doing some programming lately and faced an issue which i found weird in c#. (at least for me)
public class Foo
{
//whatever
public class FooSpecificCollection : IList<Bar>
{
//implementation details
}
public FooSpecificCollection GetFoosStuff()
{
//return the collection
}
}
I want the consumer of Foo to be able to obtain a reference to FooSpecificCollection, even perform some operations on it. Maybe even set it to some other property of Foo or smth like that, but not To be able to CREATE an instance of this class. (the only class that should be able to instatiate this collection should be Foo.
Is my request really that far-fetched? I know that people way smarter defined c# but shouldn't there be such an option that a parent class can create a nested class instance but nobody else can't.
So far I created a solution to make an abstract class, or interface available through the property and implement a concrete private class that is not available anywhere else.
Is this a correct way to handle such a situation.?
The way embedded classes work is that they, as members of the outer class, get access to private members of that outer class. But not the other way around (what is what you want).
You can shield the constructor of FooSpecificCollection, but then the Factory has to be part of FooSpecificCollection itself. It could enlist the outer class:
public class Foo
{
public class FooSpecificCollection : List<Bar>
{
private FooSpecificCollection () { }
public static FooSpecificCollection GetFoosStuff()
{
var collection = new FooSpecificCollection ();
PrepareFooSpecificCollection(collection);
return collection;
}
}
private static void PrepareFooSpecificCollection(FooSpecificCollection collection)
{
//prepare the collection
}
}
Make your nested class private and make the return value of GetFoosStuff IList<Bar> instead of FooSpecificCollection.
Also, there's a good chance that deriving from List<Bar> is a bug.
If you are creating a library for others to use, you could make the constructor internal. Anyone outside the library will not be able to access it. If you are concerned about calling the constructor in your own project, just don't call it outside the parent class.
We create classes all the time which are not directly related to other classes, but the constructors don't have to be hidden from non-related classes. We (the programmers) know the the objects are not related so we don't ever create an instance of one in the other.
There is a solution but I don't think I would use it in my App :)
The idea is to have derived class from FooSpecific which is private and can be used only inside Foo but has public constructor, so Foo can create its instances.
public class Foo
{
//whatever
public class FooSpecific
{
// Protected contructor.
protected FooSpecific()
{
}
// All other code in here.
}
// Private helper class used for initialization.
private class FooSpecificInitHelper : FooSpecific
{
public FooSpecificInitHelper()
{
}
}
// Method in foo to create instaces of FooSpecific.
private FooSpecific CreateFooSpecific()
{
return new FooSpecificInitHelper();
}
}
No, and it doesn't really make sense.
I mean the whole point is so that you could potentially return other instances; but who will be deriving from that class anyway? Certainly not any other classes (Because that would be wrong, and imply it shouldn't be hidden inside the main class), so ...

Categories

Resources