c# - how to use interface with singleton class -
as go through differences between singleton vs static class, came across 1 point can inherit interface in singleton class , can call singleton through interface multiple implementation.
i code demonstration example, how object orientation can achieve through singleton , not through static.
thanks,
although it's hard tell referring to, 1 pattern might referring multiton pattern, manage map of named instances key-value pairs.
that's factory, each instance created once:
i've modified wikipedia example bit show can derive singleton class, long concrete implementations private , within original class:
class foomultiton { private static readonly dictionary<object, foomultiton> _instances = new dictionary<object, foomultiton>(); // classic old singleton trick (prevent direct instantiation) private foomultiton() { } // can have private concrete implementations, // invisible outside world private class concretefoomultitonone : foomultiton { } public static foomultiton getinstance(object key) { lock (_instances) { foomultiton instance; // if doesn't exist, create , store if (!_instances.trygetvalue(key, out instance)) { // @ point, can create derived class instance instance = new concretefoomultitonone(); _instances.add(key, instance); } // return same ("singleton") instance key return instance; } } }
also, generally, if singleton not static class, can implement interface want. thing singleton pattern prevents instantiation of multiple instances of singleton class, doesn't mean cannot replace implementation else.
for example, if have singleton not static class:
interface icantalk { string talk(); } class singleton : icantalk { private singleton() { } private static readonly singleton _instance = new singleton(); public static singleton instance { { return _instance; } } public string talk() { return "this singleton"; } }
you can have number of different implementations:
class otherinstance : icantalk { public string talk() { return "this else"; } }
then free choose implementation want, single instance of singleton
class:
icantalk item; item = singleton.instance; item = new otherinstance(); item = new yetanotherinstance();
Comments
Post a Comment