0

我有一个单身课程

public class Singleton {
static Singleton instance;
public static Singleton getInstance() 
{
    if (instance == null) 
    {
        instance = new Singleton();
    }
    return instance;
}

考虑一个公共函数method()在类Singleton中定义。

这是在单例类中调用方法的最佳方式:

辛格尔顿。method() - 静态调用方法

或者

Singleton.getInstance.method() - 方法不是静态的?

4

7 回答 7

11

在单例类的情况下,没有使用静态方法,因为该类只有一个可用的实例,并且每个伙伴都拥有它的相同副本。

所以总是创建一个实例方法并调用:

Singleton.getInstance().method();
于 2014-02-25T10:08:49.427 回答
2

单例模式允许您控制一个类存在的实例数量 - 即只有 1 个。但该类本身仍然是一个普通类,不应该知道它的种类存在多少,因此它应该具有普通的实例方法.

使用static方法时,如果您想更改该类的实例数量,您将遇到可怕的问题。

要么使用单例,要么使用静态方法。

于 2014-02-25T10:13:44.690 回答
2

如果你想使用单例模式:

public class Singleton {
    private static Singleton sInstance;

    public static Singleton getInstance() {
        if (sInstance == null) {
            sInstance = new Singleton();
        }

        return sInstance;
    }

    // Prevent duplicate objects
    private Singleton() {

    }

    public void method() {

    }
}
于 2014-02-25T10:11:26.643 回答
2

首先,您应该确保您已将您的声明Constructor为私有,以防止任何人调用它并再次重新初始化它。如下:

private void Singleton(){
    //Initialize your private data
}

、直接调用static方法如下:

Singleton.yourMethod();

第三:非静态方法调用如下:

Singleton.getInstance().yourMethod();

这是类的一个很好的例子Singleton

于 2014-02-25T10:15:03.163 回答
1

In the first case:

Singleton.method();

method have to be static

In the second case:

Singleton.getInstance().method();

the method is not static.

So those are conceptually different

于 2014-02-25T10:08:04.830 回答
0

Singleton.getInstance().method();

is better as when called for first time instance will be null and instance is only created in getInstance().

于 2014-02-25T10:08:29.997 回答
0

Here you are having getInstance() as a static method and you have created method as a non-static or instance method.

So for a static method, Class.method_name format can be used, but for an instance method object needs to be created.

It may not be the correct syntax as shown over there:

Singleton.getInstance().method();

Singleton obj = new Singleton();
obj.method();

should be the correct format

于 2017-08-19T22:02:33.107 回答