简体   繁体   English

具有多实例管理的单例

[英]Singleton with multi instance management

I'm trying to develop something with let's say : 我正在尝试通过以下方式开发一些东西:
A class : User 一类:用户
Several instances of User : "john", "joe", ... 用户的几个实例:“ john”,“ joe”,...
I would like that each name is instanced only one time, so if the user tries to create an User wich name already exists, it returns the existing user instance. 我希望每个名称仅被实例化一次,所以如果用户尝试创建一个已经存在的用户,则它会返回现有的用户实例。
With the singleton, I can only make one instance. 使用单例,我只能创建一个实例。
How can I do that? 我怎样才能做到这一点?

What you are looking for is the factory pattern. 您正在寻找的是工厂模式。
Let the factory cache the created instances and return them as they exist. 让工厂缓存创建的实例,并在它们存在时返回它们。

You could implement it in multiple ways : static method, singleton pattern : enum class or classical singleton or still dependency injection. 您可以通过多种方式实现它:静态方法,单例模式:枚举类或经典单例或依存注入。
Note that the implementation should also consider to synchronize the access to the object that caches the users if the factory is accessed concurrently. 请注意,如果同时访问工厂,则该实现还应考虑同步对缓存用户的对象的访问。

Here is an example with the enum way and thread safe. 这是一个枚举方式和线程安全的示例。

Interface implemented by the enum (not mandatory but clearer and more extensible) : 枚举实现的接口(不是强制性的,但更清晰,更可扩展):

public interface IUserFactory {

    User getUser(String user);

}

Enum factory : 枚举工厂:

public enum UserFactory implements IUserFactory {
    INSTANCE;

    private Map<String, User> map = new ConcurrentHashMap<>();

    @Override
    public User getUser(String username) {

        User user = map.get(username);
        if (user != null) {
            return user;
        }
        synchronized (INSTANCE) {
            final User user = new User(username);
            map.put(username, user);
            return user;
        }

    }

}

Create a UserFactory class, then add a method to it, like User getUser(String name) . 创建一个UserFactory类,然后向其中添加一个方法,例如User getUser(String name)

Also, make User 's contructor package-private to make sure that only UserFactory (belonging to the same package) will be able to instantiate new User objects. 另外,将User的构造UserFactory为package-private,以确保只有UserFactory (属于同一包)才能实例化新的User对象。

For further info on factory pattern, please refer to https://en.wikipedia.org/wiki/Factory_method_pattern . 有关工厂模式的更多信息,请参阅https://en.wikipedia.org/wiki/Factory_method_pattern

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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