Singleton with Generics Argument

时间:2013-09-26 18:09:51

标签: java generics singleton

如何创建我的实例?

我总是遇到编译错误。

描述资源路径位置类型 无法对非静态类型COMPONENT ComponentManager.java进行静态引用

package component;

public class ComponentManager<COMPONENT extends Component> {

private static ComponentManager<COMPONENT> instance = new ComponentManager<COMPONENT >();

private ComponentManager() {

}

public static ComponentManager<?> getInstance() {
    return instance;
}

}

2 个答案:

答案 0 :(得分:1)

声明和实例化的语法错误。像这样创建'实例':

private static ComponentManager<? extends Component> instance = new ComponentManager< >();

答案 1 :(得分:0)

如果new ComponentManager()为空,则将getInstance()行放在instance方法内调用构造函数,否则返回instance

public class ComponentManager {

    private static ComponentManager instance;

    private ComponentManager() {

    }

    public static ComponentManager getInstance() {
        if (instance  != null) {

        } else {
            instance = new ComponentManager();
        }
        return instance;
    }

}