|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

 

 

posted on   yanqi_vip  阅读(6)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示