如何在Java中使用static制作Singleton Class?
Java中的Singleton类是什么?
当一个类一次仅包含一个对象时,该类被称为Singleton类。在单例类中,我们使用getInstance()方法代替构造函数。
在Java中制作单例类的程序
//该程序将使用static创建一个单例类
public class SingletonClassUsingStatic
{
public static void main(String args[])
{
//创建类的对象。
MySingleton ms = MySingleton.getInstance();
ms.testSingleton();
}
}
//创建单例类并创建私有构造函数。
class MySingleton
{
private static MySingleton instance;
static
{
instance = new MySingleton();
}
private MySingleton()
{
System.out.println("This is Singleton Object..");
}
public static MySingleton getInstance()
{
return instance;
}
public void testSingleton()
{
System.out.println("Class Created..");
}
}输出结果
This is Singleton Object.. Class Created..
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短