views:

55

answers:

1

This is how I understand I can implement the singleton pattern in C#:

public class ChesneyHawkes{
    private static ChesneyHawkes _instance = new ChesneyHawkes();
    public ChesneyHawkes Instance {get{return _instance;}}

    private ChesneyHawkes()
    {
    }

}

What if I want to provide a single instance of an object, so that there can only ever be one, make the access to it public, but only allow it to be created or replaced by another singleton.

//   The PuppetMaster should be the only class that 
//   can create the only existing Puppet instance.

public class PuppetMaster{

    private static PuppetMaster_instance = new PuppetMaster();
    public static PuppetMaster Instance {get{return _instance;}}

    // Like a singleton but can be replaced at the whim of PuppetMaster.Instance
    public static Puppet PuppetInstance {get {return Puppet;}}

    private PuppetMaster()
    {

    }

    public class Puppet{
          // Please excuse the pseudo-access-modifier
          puppetmasteronly Puppet(){

          }
    }
}


//   To be accessed like so.
PuppetMaster.Puppet puppet = PuppetMaster.Instance.PuppetInstance;
+1  A: 

You don't really need more than one singleton for that. Look at this example:

using System;

// interface for the "inner singleton"
interface IPuppet {
    void DoSomething();
}

class MasterOfPuppets {

    // private class: only MasterOfPuppets can create
    private class PuppetImpl : IPuppet {
        public void DoSomething() {
        }
    }

    static MasterOfPuppets _instance = new MasterOfPuppets();

    public static MasterOfPuppets Instance {
        get { return _instance; }
    }

    // private set accessor: only MasterOfPuppets can replace instance
    public IPuppet Puppet {
        get;
        private set;
    }
}

class Program {
    public static void Main(params string[] args) {
        // access singleton and then inner instance
        MasterOfPuppets.Instance.Puppet.DoSomething();
    }
}
Paolo Tedesco
Thanks I think this is along the lines of what I want to do, although other classes would also be able to implement IPuppet so, there probably wouldn't be, but could be more than one IPuppet in my project.I really want an object that there can only ever be one instance of at a time but can be replaced by creating it more than once. However, I'm not very good at thinking in Interfaces at the moment which I think makes me a poor user of the language, it's something I really need to improve my understanding of. Your example certainly allows private creation and public access so thank you.
panamack
It is true that someone else might implement IPuppet, but the interface and the singleton class in this example are making clear how they should be used, and that is the important thing, as you cannot prevent every possible misuse of your application. Even with a regular singleton, someone might still instantiate an extra instance using reflection...
Paolo Tedesco