-1

我搜索但没有找到 Java Singleton 函数或类的任何正常信息,那么任何人都可以解释我为什么需要它们吗?他与其他功能有什么区别?

4

4 回答 4

3

单例模式用于只应由一个实例存在的类。单例的用途及其值应该在整个应用程序中保持一致。

单例通常用于特殊环境变量、数据库连接、工厂和对象池。

于 2012-09-05T13:02:29.687 回答
2

Singleton 用于只创建一个 Object 实例

public class Singleton {

    private static Singleton uniqueInstance;

    // other stuff
    private Singleton()
    {

    }
    public static Singleton getInstance()
    {
        if(uniqueInstance == null)
        {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
    // other methods
}

这是让您了解单例模式的简单示例

于 2012-09-05T13:07:18.557 回答
1

Sometimes it's appropriate to have exactly one instance of a class: window managers, print spoolers, and filesystems are prototypical examples. Typically, those types of objects—known as Singletons

没有什么像Singleton function,我们通常使用Singleton Classes

http://www.javapractices.com/topic/TopicAction.do?Id=46

于 2012-09-05T13:03:25.917 回答
1

好的,这个类只有一个对象。为了制作一个单例类,将构造函数设为私有并定义一个静态方法来获取这样的类对象

   public class yourclassname{
   private yourclassname{}
   public static yourclassname getMySongAlarmdb(Context c)
            {
                if (myobject == null){
                    myobject = new yourclassname;
                }
                return myobject;
            }
    }
于 2012-09-05T13:07:11.037 回答