|NO.Z.00045|——————————|BigDataEnd|——|Java&static关键字继承.V05|——|Java.v05|Singleton/SingletonTest类|框架实现|
一、Singleton和SingletonTest类的框架实现
### --- 案例题目(重中之重)
~~~ ——> 编程实现Singleton类的封装。
~~~ ——> 编程实现SingletonTest类对Singleton类进行测试,要求main方法中能得到且只能得到该类的一个对象。
二、编程代码
### --- 编程代码:编程实现SingLeton类的封装
/*
编程实现Singleton类的封装
*/
public class Singleton {
// 2.声明本类类型的引用指向本类类型的对象,使用private static关键字共同修饰
//private static Singleton sin = new Singleton(); // 饿汉式
private static Singleton sin = null; // 懒汉式
// 1.私有化构造方法,使用private关键字修饰
private Singleton() {}
// 3.提供公有的get方法负责将对象返回出去,使用public static关键字共同修饰
public static Singleton getInstance() {
//return sin;
if(null == sin) {
sin = new Singleton();
}
return sin;
}
}
三、编程代码:编程实现singletontest类的测试
### --- 编程代码:编程实现singletontest类的测试
/*
编程实现Singleton类的测试
*/
public class SingletonTest {
public static void main(String[] args) {
// 1.声明Singleton类型的引用指向该类型的对象
//Singleton s1 = new Singleton();
//Singleton s2 = new Singleton();
//System.out.println(s1 == s2); // 比较变量s1的数值是否与变量s2的数值相等 false
//Singleton.sin = null; 可以使得引用变量无效
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2); // true
}
}
四、编译打印
### --- 编译
C:\Users\Administrator\Desktop>javac SingletonTest.java
### --- 打印输出
C:\Users\Administrator\Desktop>java SingletonTest
true
Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
——W.S.Landor
浙公网安备 33010602011771号