简体   繁体   中英

Have constructor resolve to an existing instance

I'm curious if there's a way to tell a class being constructed to reference an existing instance.

For example:

class MyClass
{
    string _name;

    static List<MyClass> _existing = new List<MyClass>();

    MyClass(string name)
    {
        foreach(MyClass existing in _existing)
        {
            if (existing._name == name)
            {
                // Set this instance to "existing"
                return;
            }
        }
        _name = name;
        _existing.Add(this);
    }
}

I think you need to implement a holder of the particles, that can direct creation or re-use to existing objects. The constructor of each class, cannot be responsible to see if it already exists, since merely newing it up to inspect, allocates resources for it. Your particle holder (Single instance) would then use a dictionary/hash/list/collection to return existing based on name, or create and cache new instances for future use.

I'm not sure if this the best approach to solve your real problem, because this sounds like a typical xy-problem. Maybe you should get familiar with singletons or dependency injection where you can control this in detail.

However, to solve this concrete issue you could use a Dictionary<string, MyClass> :

class MyClass
{
    string _name;

    static Dictionary<string, MyClass> _existing = new Dictionary<string, MyClass>();

    private MyClass(string name)
    {
        _name = name;
    }

    public static MyClass GetFromName(string name)
    {
        if(_existing.TryGetValue(name, out MyClass instance))
            return instance;

        MyClass newInstance = new MyClass(name);
        _existing.Add(name, newInstance);
        return newInstance;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM