开发者

What design pattern should I be utilizing if I require a group of singleton classes to be searchable/retrievable?

开发者 https://www.devze.com 2023-02-23 08:02 出处:网络
I need to have only single instances of a bunch of cla开发者_开发百科sses in my project. However, I need them to be searchable/retrievable (like an array). What design pattern should I be utilizing?I\

I need to have only single instances of a bunch of cla开发者_开发百科sses in my project. However, I need them to be searchable/retrievable (like an array). What design pattern should I be utilizing?


I'm not sure if I understand correctly, but I think that maybe you need a Dependency Injection container. Take a look into Inversion Of Control/Dependency Injection patterns.

Microsoft Patterns &Practices provides an implementation of DI container called Unity. There are other open source projects like Castle Windsor and others

You can register types in the container, specifying, for example, that you want some types to be singleton:

IUnityContainer container = new UnityContainer();
container.RegisterType<MyClass>(new ContainerControlledLifetimeManager()); 
...
var mySingletonType = container.Resolve<MyClass>(); // All calls to this method will 
  // return the same instance

IoC/DI is actually more than this, but I hope that this example is useful for you as an start point.


Encapsulate the collection in a Singleton. That effectively makes all the contained instances Singletons as well.

C# example:

public class Singleton
{
    public static Singleton Current { get; }

    public IEnumerable<IFoo> Foos { get; }
}

You can enumerate and query the Foos by accessing Singleton.Current.Foos. Since the Singleton encapsulates the IFoo instances, it can make sure that there's only one instance of each, but you can also make each of the IFoo implementations into Singletons. However, it's not necessary.


As others have noted, you might be better off rethinking your design and using dependency injection.

But what you're describing is similar to the Multiton Pattern, so that might also be worth looking at.


Java version for Mark's solution:

  public class Singleton {
      public static Singleton instance = new Singleton();
      public Set<Singleton> singletons = new HashSet<Singleton>;

      //Instance can only be created inside this class
      private Singleton(){

      }  

      static {
        // Add all the singleton's to set
        singletons.add(MyArray.class);
        ... 
      }

      public static Singleton getInstance() {
             return instance;
      }

      public static Set getSingletons() {
             return singletons;
      } 


  }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号