I am trying to implement a Singleton base class in my Unity3d project. But attempting to access the instance of a Singleton raises compiler errors:
Type 'Singleton' does not contain a definition for 'getPlaneTextureType' and no extension method 'getPlaneTextureType' of type 'Singleton' could be found (are you missing a using directive or an assembly reference?)
Do I need to override the method/property instance for each class that derives from Singleton? Ie, change the return type to the child class type? Or is there 1 simple change I can make to the base class Singleton that will fix this? Like for example; using c++ like templates?
public class Singleton : MonoBehaviour {
#region Static Variables
private static Singleton _instance = null;
#endregion
#region Singleton Class Generation
public static Singleton instance {
get { return _instance; }
}
protected Singleton() { }
void Awake() {
if (_instance != null) {
GameObject.Destroy( this );
return;
}
_instance = this;
}
#endregion
}
public class TerrainManager : Singleton {
public PlaneTexture getPlaneTextureType() { }
}
// Usage that throws compiler error: Type 'Singleton' does not contain a definition for 'getPlaneTextureType' and no extension method 'getPlaneTextureType' of type 'Singleton' could be found (are you missing a using directive or an assembly reference?)
TerrainManager.instance.getPlaneTextureType();
Sometimes you want a Singleton in Unity to be just a plain Singleton Design pattern without it being a MonoBehaviour.
Othertimes you need your Singleton to be a MonoBehaviour. When it must be a MonoBehaviour you can do this to avoid calling new which you can't do on MonoBehaviours.
Solution
Makes a Singleton out of a MonoBehaviour
public class Singleton : MonoBehaviour
{
private static Singleton _instance;
// Will be called before anything, don't even worry about it, instance be initialized.
void Awake()
{
_instance = this;
}
public static Singleton getInstance()
{
return _instance;
}
}
This should also allow you to inherit from this Singleton like this:
public class Singleton2 : Singleton
{
}
Also the Destroy() code you are using won't be a good idea unless you are protecting the Singleton from being destroyed on level change with DontDestroyOnLoad()
Other Solution
You can find it here: Unity Wiki Singleton It is the same code Imran posted but he forgot to include the reference link where he got it from.
You can either move getPlaneTextureType() method into the Singleton class for TerrainManager.instance.getPlaneTextureType() to work you can change getPlaneTextureType() into a static method and called it as such... TerrainManager.getPlaneTextureType().
Inheritance won't help you implement a singleton in C# very well. The reason is that if you put the static field in the base class, it is the same static field for across all inherited classes. This exactly what you don't want. You want a static field and/or property in each inherited class that is different.
It's not really that much code to implement one in the first place so inheritance isn't really letting you reuse a lot of code. This is your basic singleton template:
public class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton() { }
public static Singleton Instance { get { return instance; } }
}
I would just copy and paste that every time I needed one, but I find myself using the singleton pattern only sparingly.
generally you applying singleton for
"It is a design pattern that restricts the Instantiation of a class to one object. And, if you're here, you probably want to use that basically for implementing Global Variables. For any other usage"
Now try for implementation
Other help plz link
Related
Note: Even though there are a lot of similar questions, non that i have found answered my question.
Problem:
I would like to implement a class in C# which uses the singleton pattern in the following way.
namespace DAL
{
public class CDAL : IDAL
{
/* Singleton Pattern */
private CDAL instance = null;
private CDAL()
{
}
public IDAL getInstance()
{
if (instance != null)
{
return instance;
}
else
{
CDAL.instance = new CDAL();
return CDAL.instance;
}
}
}
}
the problem is that instance and the method getInstance should be static, as i want to 'ask' the class for that instance and not an object.
but using c# i can't seem to do anything static in an interface.
how can i solve this?
You're right, you cannot do anything static on an interface, since it does not make any sense.
Use an abstract class instead of the interface to implement static logic.
It does not make any sense creating an interface with a static member.
Interfaces are a contract while the static member is always accessed by the class name, not the instance name. so briefly your interface does not know which the correct instance implementing the right logic.
in your case you don't need your method getInstance() to be defined in the interface.
Interface when used with Singleton is often just for unit testing purposes
Getting used to some new code and have a question. All over it, I am seeing the following
file1.cs :
MyClass myInstance = MyClass.Instance();
...and then in the definition of MyClass there is...
MyClass.cs :
public class MyClass {
// etc. etc.
static readonly MyClass _instance = new MyClass();
public static MyClass Instance() {
return _instance;
}
// etc. etc.
}
What's the reason for doing that as opposed to just in file1.cs :
MyClass myInstance = new MyClass();
?
Because its using single ton pattern that is the reason...
Read : Singleton - The singleton pattern is a design pattern that is used to ensure that a class can only have one concurrent instance. Whenever additional objects of a singleton class are required, the previously created, single instance is provided.
Read : Singleton with proper example
it is a "singleton pattern" you can read about it here
http://csharpindepth.com/Articles/General/Singleton.aspx
This is the singleton pattern. That's why a method is used to get the instance.
Singleton pattern is used, when we want only one instance of a class be used in our app. We don't want the consumers of our app have the right to build more than one instances.
For a detailed description of the singleton pattern, please have a look here.
This is a Singleton Pattern sometimes a new instance is not the best way to do something.
An example of this is a logger. There is no need to instantiate a logger every time one is needed hence the singleton pattern is useful.
And yet another theory about the singleton...
You use it also in situations when you would like to have a common object shared by different parts of your application. Sometimes it might be necessary that you are forced to turn a static class into a singleton so that you can use if for data binding (a static class cannot be bound).
Some typical singletons that live as long as the application lives can be settings, some kind of cache, a backgrou file uploader with file watcher etc. etc...
I would advise you to use a property instead of a function. It is cleaner, more convenient for debugging and mock testing.
Note that by using a static constructor (as you are already doing), the initialization of _instanceis thread-safe.
Note : The implementation of the other methods should not be static.
Find below the complete implementation of the singleton pattern:
public class MyClass
{
static MyClass _instance = new MyClass();
public static MyClass Instance
{
get
{
return _instance;
}
set { _instance = value; }
}
public void DoStuff()
{
//etc...
}
private MyClass()
{
}
}
And you use it in other classes this way :
MyClass.Instance.DoStuff();
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...)
As it is not possible to override a static class in c#, if i want to override a method I generally define a delegate matching the signature of the static method, then modify the method along the lines of:
public static void foo(int bar)
{
if (delegatename!=null)
{
delegatename.Invoke(bar);
}
else
{
//execute previous code as normal
}
}
I feel a twinge of guilt, knowing this is a bit messy.
Can anyone suggest a neater solution to this problem (other than rewriting the original structure)
It seems that you are using the static class as a way to provide a single access point to some resource in your application. If it is the case, you should consider to use an implementation of Singleton design pattern. Doing it, you could take advantage of use inheritance on your non-static classes.
public abstract class Base { ... }
public class Impl : Base { ... }
public class Singleton : Impl
{
#region Static Members
static readonly Singleton _instance = new Singleton();
static Singleton() { }
static public Singleton Instance
{
get { return _instance; }
}
#endregion Static Members
#region Instance Members
private Singleton() { }
// Method overrides goes here...
#endregion Instance Members
}
A deeper discussion on how to implement the singleton design pattern on C# can be found on Implementing the Singleton Pattern in C# article.
Consider using dependency injection, as static singletons make test isolation essentially impossible and re-usability extremely painful.
Singletons are cool, just don't do it using statics. There are many resources on "dependency injection," which Google can easily find for you.
Although a static class has only one instance and can't be instantiated, a class with a private constructor can't be instantiated (as the constructor can't be seen), so every time you call this class, this is the same one instance?
Factory classes always follow the last convention (instance class with private constructor). Why is this?
Thanks
There's nothing stopping the class with the private constructor from having a public static method which returns instances of the class:
public class NoPublicConstructor
{
private NoPublicConstructor()
{
}
public static NoPublicConstructor NewInstance()
{
return new NoPublicConstructor();
}
}
As you can see, the static method does not return the same one instance.
edit: One of the reasons factory classes do this is to be able to separate responsibility in future versions: while your code always calls the factory creation method, the author may move all the "guts" out of that class into a different one and your code won't need to know the difference. Calling that class' (public) constructor ties it to an extent to the original class implementation.
You can't* get an instance from outside the class, but you can from inside. A static method or an inner class can create and return an instance of the class with a private constructor. The static class cannot be instanced by anything.
class Foo
{
private Foo()
{
}
public class Bar
{
public Bar()
{
}
public Foo GetFoo()
{
return new Foo();
}
}
}
..
Foo.Bar fooBar = new Foo.Bar();
Foo foo = fooBar.GetFoo();
Edit: *I use the term "can't" loosely. Brian Rasmussen pointed out in the comments to the OP that another method to obtain an instance is through a call through System.Runtime.Serialization.FormatterServices, and this is external to the class itself.
Foo foo = (Foo)System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject(typeof(Foo));
Creating a class with private constructor is the common pattern for implementing a "Singleton" object.
The Singleton usually will instantiate an instance of itself, and only allow access to it through a static "Instance" property, which means there's only ever one instance of the class.
The advantage of using a Singleton over a purely static class is that you can utilize interfaces and different implementation classes within the singleton. Your "Singleton" might expose an interface for a set of methods, and you can choose which exact implementation class to instantiate under the covers. If you were using a purely static class, it would be hard to swap out a completely different implementation, without impacting other code.
The main downside of Singleton is that it's difficult to swap out the implementation class for testing, because it's controlled within the Singleton private methods, but there are ways to get around that.