关于Singleton不确定

时间:2015-01-23 15:57:02

标签: java singleton

如果我有一个单身类,如:

public class MySingleton(){
    private static MySingleton istance;
    private int element;

    private MySingleton(){element = 10;}     

    public static MySingleton getIstance() {
        if(istance == null)
            istance = new Mysingleton();
        return istance;
    }
    public void setElement(int i ){
        element = i;
    }
    public int getElement(){
        return element;
    }
}

我希望通过调用

来更改元素的值
MySingleton.getIstance().setElement(20)

它会改变istance的元素值吗?这是一个例子:

... main () {
    MySingleton.getIstance().setElement(20);
    System.out.prinln(MySingleton.getIstance().getElement());
    // It displays 10, why ?

3 个答案:

答案 0 :(得分:2)

我建议您使用enum,因为它更简单且线程安全(但不是您的getter / setter)

public enum MySingleton() {
    INSTANCE;

    private int element = 10;

    public void setElement(int element) { this.element = element; }
    public int getElement() { return element; }
}

MySingleton.INSTANCE.setElement(20);
System.out.prinln(MySingleton.INSTANCE.getElement()); // prints 20.

答案 1 :(得分:1)

我不确定上面的代码块是否被复制或只是重新输入,但是我看到了一些基本的编译问题 - 当你在getInstance中设置MySingleton时,你需要检查资本。此外,您的班级声明不应该有(括号)。修好这两件东西并运行基本主,我得到了20。

这与你所拥有的相同 - 没有同步或其他任何东西,但在一个线程上似乎没有必要。

public class MySingleton{
    private static MySingleton istance;
    private int element;

    private MySingleton(){element = 10;}     

    public static MySingleton getIstance() {
        if(istance == null)
            istance = new MySingleton();
        return istance;
    }
    public void setElement(int i ){
        element = i;
    }
    public int getElement(){
        return element;
    }

    public static void main(String[] args) {
        System.out.println(MySingleton.getIstance().getElement());
        MySingleton.getIstance().setElement(20);
        System.out.println(MySingleton.getIstance().getElement());
    }

}

应该有

的输出
10
20

答案 2 :(得分:-1)

我不确定你的代码是否真的有用,azurefrog如何说,让你的代码同步,你需要在行public static getIstance() {中设置返回类型。

相关问题