CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11
  1. #1
    Join Date
    Oct 2003
    Location
    .NET2.0 / VS2005 Developer
    Posts
    7,104

    Singleton Pattern problem (inheritance)

    suppose i have a class i want as a singleton, and i write:

    Code:
    class Thing{
      static Thing me;
    
      private Thing(string param){
        //do some stuff
      } 
    
      static getInstance(){
        if(me ==null)
          me = new Thing();
    
        return me;
      }
    }
    how do i now inherit this. the new inherited version needs to have a constructor that does something different.. i cant override getInstance in the child class, to call new ChildThing() because static methods cannot be overridden

    Code:
    class ChildThing : Thing{
      
    
      private ChildThing(string param){
        //do some more stuff
      } 
    
      static override getInstance(){
        if(base.me ==null)
          base.me = new ChildThing();
    
        return base.me;
      }
    }

    so how does one write a singleton that is inheritable?
    "it's a fax from your dog, Mr Dansworth. It looks like your cat" - Gary Larson...DW1: Data Walkthroughs 1.1...DW2: Data Walkthroughs 2.0...DDS: The DataSet Designer Surface...ANO: ADO.NET2 Orientation...DAN: Deeper ADO.NET...DNU...PQ

  2. #2
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: Singleton Pattern problem (inheritance)

    I don't think Singleton classes can be inheritted. As you have already mentioned that the constructor is private and the getInstance method is static.

    So having inheritence in this case is impossible.

  3. #3
    Join Date
    Feb 2005
    Location
    Israel
    Posts
    1,475

    Re: Singleton Pattern problem (inheritance)

    Long ago I wanted to do the same thing: I wanted to make the base class a singleton, and force the childs to be singletons as well without coding anything in the child classes to indicate it.

    From OO point of view, this cannot be achieved: static methods can obviousely not be virtual, and the creational pattern of the base class do not suggest anything about the creational pattern of the childs.

    I thought about implementing this in Aspect Oriented Programming - to implement an Attribute called Singleton attribute, which I can place on the base class and then all the hirerchy will be singletons. Unfortunately, this involves very difficult code interception mechanism and I couldn't get it to work. I am almost possible that this can be achieved though.

    So, I would suggest seeking the aid of other design patterns. For example you can have a Repository class which hold instances of classes from the hirerchy tree, and using a FactoryMethod, given a Type return the correct object. This will give you the exact result as singleton would.

  4. #4
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: Singleton Pattern problem (inheritance)

    You can do this using templates in C++ : see here. Read my comments in the replies about making the constructor of the derived class private before making any judgements.

    Possibly you could apply the same methodology using generics in C#.

    e.g.

    Code:
        public class Singleton<T> where T : new()
        {
            static T _instance = default(T);
    
            protected Singleton()
            {
            }
    
            static public T Instance
            {
                get
                {
                    if (_instance == null)
                    {
                        _instance = new T();
                    }
    
                    return _instance;
                }
            }
        }
    
        public class MySingleton : Singleton<MySingleton>
        {
            public MySingleton()
            {
            }
        }
    Unfortunately the inherited classes have to have a public constructor, because we don't have friends in C# (no I don't have any friends... ) but it might get close to what you want to do. I think you can probably exert better checking - i.e. throw an exception if the constructor isn't being called by the base class - but you can't hide the constructor as far as I can see.

    Darwen.
    Last edited by darwen; February 22nd, 2006 at 04:53 PM.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

  5. #5
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: Singleton Pattern problem (inheritance)

    Or you can use Factory Pattern. Create standalone class (it can be singleton itself) which will keep instances of your "singleton" classes and ask that class for instances of your classes. Yes, you have to have public constructors in your classes, but I don't think it is a great complication.

    I imagine it like it (just fragment). I design it parametrizable. There are many variations.
    Code:
    public class ThingFactory
    {
      private static instances = new Hashtable();
      
      public static object GetInstance(Type type)
      {
        Object instance = instances[type];
        if (instance == null)
        {
           instance = Activator.CreateInstance(type);
           instances[type] = instance;
         } 
    
        return instance;
      }
    }
    
    // and use it
    ChildThing childThing = ThingFactory.GetInstance(typeof(ChildThing);

    Maybe, someone could try to solve this with generics. Similar to darwen's solution, but I am not sure how it would work in C# and I cannot try it.
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

  6. #6
    Join Date
    Oct 2003
    Location
    .NET2.0 / VS2005 Developer
    Posts
    7,104

    Re: Singleton Pattern problem (inheritance)

    thanks for the replies guys! i'll be putting them into practice!

    one thing i wondered; someone said that obviously static methods cannot be virtual or override.. i want to know why?
    "it's a fax from your dog, Mr Dansworth. It looks like your cat" - Gary Larson...DW1: Data Walkthroughs 1.1...DW2: Data Walkthroughs 2.0...DDS: The DataSet Designer Surface...ANO: ADO.NET2 Orientation...DAN: Deeper ADO.NET...DNU...PQ

  7. #7
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: Singleton Pattern problem (inheritance)

    Quote Originally Posted by cjard
    one thing i wondered; someone said that obviously static methods cannot be virtual or override.. i want to know why?
    Static members belong to the Class itself and not to the instance, that is the reason why we cannot use virtual modifier with static. For the same reason we cannot override a static member in the inheritted class. But we can definitely hide it.

    Is it necessary to override the static constructor. You can Hide it in the inheritted class. Does this piece of code make any sense.
    Code:
    public class Singleton
    {
    //static member
    private static Singleton instance;
    //protected contructor so that we can access it from the derived class
    protected Singleton() {}
    //static method to create the instance
    public static Singleton Instance
    {
    	get
    	{
    	 if (instance == null)
    	 {
    		instance = new Singleton();
    	 }
    	 return instance;
    	}
    }
    }
    
    //derived class
    public class inSingleton : Singleton
    {
    // static member for saving derived class's instance
    private static inSingleton instance; 
    //constructor
    private inSingleton() {}
    //hide the public Instance method of base class
    public new static inSingleton Instance
    {
    	get
    	{
    	 if (instance == null)
    	 {
    		instance = new inSingleton();
    	 }
    	 return instance;
    	}
    }
    }



  8. #8
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    Re: Singleton Pattern problem (inheritance)

    I am just wondering.. why can you not make the constructor as protected instead or private. That solves the problem of creation of the base part of the objects.

    Also, I don't know if the Generics in C# can handle this but in C++ templates (and Multiple Inheritance) are quite capable of policy based class design. You can have a policy class "SingletonCreator" (and more alternatives, if applicable like DoubletonCreator/MultitonCreator) and then publicly inherit it through the host class that you have as "Thing". Additionaly, you can have more policies and inherit from them as well. MI is not available in C#, interfaces instead of classes can help.

    But to me this would be like an over-kill if you only want singleton-ness. The making of the constructor (and destructor) protected and having static getInstance (and static deleteInstance) should serve the purpose. Shouldn't it? Regards.

  9. #9
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    Re: Singleton Pattern problem (inheritance)

    Quote Originally Posted by Shuja Ali
    Code:
    public class Singleton
    {
    //static member
    private static Singleton instance;
    //protected contructor so that we can access it from the derived class
    protected Singleton() {}
    //static method to create the instance
    public static Singleton Instance
    {
    	get
    	{
    	 if (instance == null)
    	 {
    		instance = new Singleton();
    	 }
    	 return instance;
    	}
    }
    }
    
    //derived class
    public class inSingleton : Singleton
    {
    // static member for saving derived class's instance
    private static inSingleton instance; 
    //constructor
    private inSingleton() {}
    //hide the public Instance method of base class
    public new static inSingleton Instance
    {
    	get
    	{
    	 if (instance == null)
    	 {
    		instance = new inSingleton();
    	 }
    	 return instance;
    	}
    }
    }


    Shuja, having a different static instance member in the derived would be better since you may want one single base object and/or one single derived object at any time, basically depends on what cjard wants as the expected behaviour. In case he doesn't the GetInstance should not be there in the base and the base should be made abstract. Regards.

  10. #10
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: Singleton Pattern problem (inheritance)

    I think it is because classes in C# are not true objects unlike e.g. in Smalltalk. Instance of Type is just a structure describind the class, not the class itself. (See that you have to use Activator if you want create instance of a Type at runtime).

    It will be difficult and confusing to have same semantic for methods of objects and something else. In other words, it is by C# design. It is nothing which would be ordered by OOP paradigm. But from my practice I can see, that this is not important limitation.
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

  11. #11
    Join Date
    May 2010
    Posts
    1

    Smile Re: Singleton Pattern problem (inheritance)

    For those of you still looking for an implementation for a singleton Parent/Base class in C++ here is an article I found that you all may find useful. Shows the template class method as well.

    http://www.yolinux.com/TUTORIALS/C++Singleton.html

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured