Creating a Generic Singleton

Generic Singleton T

The problem with a generic singleton factory is that since it is generic you do not control the "singleton" type that is instantiated so you can never guarantee that the instance you create will be the only instance in the application.

If a user can provide a type to as a generic type argument then they can also create instances of that type. In other words, you cannot create a generic singleton factory - it undermines the pattern itself.

Creating a generic singleton

Do you mean something like this?

protocol Initializable: class { init() }

private var instances = [String: Initializable]()

func singletonInstance<T: Initializable>(_ ty: T.Type = T.self) -> T {
let name = NSStringFromClass(ty)
if let o = (instances[name] as? T) {
return o
}
let o = ty()
instances[name] = o
return o
}

An use-side of it, for instance.

class Foo: Initializable { required init() {} }
class Bar: Initializable { required init() {} }

let foo1 = singletonInstance() as Foo // or `singletonInstance(Foo.self)`
let foo2 = singletonInstance() as Foo
assert(foo1 === foo2)

let bar1 = singletonInstance() as Bar
let bar2 = singletonInstance() as Bar
assert(bar1 === bar2)

(I've tested the code above and got it to work in Swift 1.2.)

Should you create a Generic Singleton class in java?

You asked two separate questions - the first being "Should You create a Generic Singleton class..." and "Is there a good way to do this (create a Generic Singleton class)".

To answer the first question, I would say no, do not attempt to create generic singleton classes, as making a class a singleton defeats the purpose of using generics.

By very nature, generics allows you to create a class that supports multiple types of data. However, if it's a singleton, only one instance of the class is ever intended to be used, and therefore, you should already know the data-types you'll be using for the duration of the program.

You cannot reference generic type parameters from a static context, as the static context is shared across all instance members of a class, which could include classes of various differing generic types.

To answer your second question, alas, also no, there is no elegant way of doing this. With additional context we may be able to suggest a better model to use to accomplish what you want.

Update in response to your update

Your CacheManager object shouldn't need to know the generic type of the caches that it's managing, in order to do housekeeping tasks. The CacheManager can simply be initilized as a singleton class without generic type parameters, such as:

public class CacheManager {

// No generic type information should be required.
private static final CacheManager singletonInstance = new CacheManager();
// This will allow a 'Cache' of any type to be registered.
private Map<String, Cache> map = new HashMap<>();

The housekeeping and cache maintenance tasks shouldn't be concerned with the types of data that the client is keeping, but rather, you may have to create an additional data structure to support the time the client registered certain keys/values, and handle the removal of them.

To accomplish tracking the values that the client places in the Cache objects, perhaps you could simply include a map in the Cache class that maps the Key K to a long where you could store a timestamp for the last value update, then simply have the CacheManager query the cache object's keys for the last updated timestamp - this could even be iterated over with the entry set.

How to make a singleton for a generic class in Swift

The fundamental problem here is that you're creating a whole family of singletons (one for each parameterized type) and each singleton needs to be stored (or referenced from) the static context. And the singletons need to be indexed by the type that they store.

I suggest creating a single, global dictionary in which to store your singletons, indexed by string descriptions of their types:

var singletons_store : [String, AnyObject]

Then in your computed shared variable you look in that store for the singleton that corresponds to a parameterized type:

class var shared : APIClient<T> {
let store_key = String(describing: T.self)
if let singleton = singletons_store[store_key] {
return singleton as! APIClient<T>
} else {
let new_singleton = APIClient<T>()
singleton_store[store_key] = new_singleton
return new_singleton
}
}

How to make a generic singleton base class C#

The problem is your generic constraint where T : class, new(). The new() constraint requires a public, parameterless constructor on T. There is no way around this; you need to provide such a constructor in Permission Controller.

how to create a generic singleton class in Unity?

if instance was null, Why GameObject to add to AddComponent ?

If the instance of the script you want to create is null if (_instance == null):

1.Create new GameObject

GameObject singleton = new GameObject();

2.Create new instance of that script and attach it to the GameObject that is created above. In Unity, a component must be attached to a GameObject. The AddComponent function is used to attach a component to a GameObject.

_instance = singleton.AddComponent<T>();

Why use that FindObject function ?

If the instance of the script you want to create is null if (_instance == null), check if that script instance already exist in the scene. The FindObjectOfType function is used to find this type of script only. Let's say that we have a script called SceneLoader and we pass SceneLoader to the Singleton class, it will check if an instance of SceneLoader is already in the scene and return that instance of it. It will return null if it does not exist.

Why use Singleton in Unity?

You use it when you only want to have one instance of a type of script in the scene. Also, with DontDestroyOnLoad, it means that this instance will still be there even when next scene is loaded. It will not be destroyed like other scripts.

please give to me Code Review

You can ask for code improvement on the codereview site. If you are new to Unity you can find Unity project tutorials on their site that can get you started easily here.

Generic Singleton T

The problem with a generic singleton factory is that since it is generic you do not control the "singleton" type that is instantiated so you can never guarantee that the instance you create will be the only instance in the application.

If a user can provide a type to as a generic type argument then they can also create instances of that type. In other words, you cannot create a generic singleton factory - it undermines the pattern itself.

Implementing a singleton in a generic Typescript class

In C#, each instantiation (set of type arguments) of a generic class gets its own set of static members. This means you can write a singleton pattern where you have one instance for Foo<int>, another for Foo<string>, and so on. This is possible because generics are manifest at runtime -- the runtime system actually knows what generics are and can allocate new objects for each type instantiation. Additionally, the static side of a class can reference the type parameters of that class (this is a consequence of the runtime semantics).

In TypeScript, this is not the case. There is only one constructor function per class, generic or otherwise. This means that the static side of the class cannot "see" the generic type parameters, because for any class X<T> with a static member y, there is only one runtime slot for X.y.

The singleton pattern for classes is generally a poor fit for TypeScript; see How to define Singleton in TypeScript . I think you have some XY problem going on here so I can't recommend any concrete alternative without more information on what your use case is (maybe post a separate question).

Also, you should never have empty interfaces in TypeScript. Types are compared structurally, so any two empty types are compatible, and you can assign anything to a variable typed as an empty interface.

Create a Singleton class with generic instance variable?

If you are potentially putting in A<T>s of heterogeneous types into the map, the map needs to be declared as with a wildcard:

private HashMap<String, A<?>> map = new HashMap();

You would then obtain a value from the map thus:

    // The cast was only necessary because A by itself is a raw type.
HashMap.Entry<String, A<?>> pair = it.next();
A<?> a = pair.getValue();
Future<?> future = a.getFuture();
// Note that future.get() yields an Object

And put it into the map like:

public void doSomething(Future<?> future, String id){
...
A<?> a = new A<>(future, null);
map.put(id, future);
...
}

If you need the T return type of the future in doSomething, you can declare a type variable on the method:

public <T> void doSomething(Future<T> future, String id){


Related Topics



Leave a reply



Submit