Java单例模式

1.单例模式类Singleton

package com.xkzhangsan.singleton;

public class Singleton {
    private static final Singleton singleton = new Singleton();

    // 限制产生多个对象
    private Singleton() {
    }
    
    // 通过该方法获得实例对象
    public static Singleton getSingleton() {
        return singleton;
    }
    
    // 类中其他方法,尽量是static
    public static void doSomething() {
        System.out.println("Singleton.doSomething...");
    }
}

2.测试类

package com.xkzhangsan.singleton;

public class Client {
    
    public static void main(String[] args) {
        
        for (int i = 0; i < 3; i++) {
            Singleton singleton = Singleton.getSingleton();
            singleton.doSomething();
        }
    }

}

 

参考:设计模式之禅

GitHub地址:https://github.com/xkzhangsan/java-designpattern-practice

上一篇:Java编程思想白话一:对象导论


下一篇:Java学习笔记——关于Java向上转型的深入探究