Singleton Pattern (单例模式)
- 单例模式,确保某个类只能生成一个实例
- 单例模式的构造方法必须定义为私有(private)的
- 必须要定义一个静态(static)的方法,作为生成这个对象实例的入口
- package com.singleton;
- class SingletonTest
- {
- private static SingletonTest singletonTest = new SingletonTest();
- static
- {
- System.out.println("======java 静态代码块========");
- }
-
-
- private SingletonTest()
- {
- System.out.println("java实现单例模式");
- }
-
- public static SingletonTest getInstance()
- {
-
- return singletonTest;
- }
-
- }
-
- public class Singleton
- {
- public static void main(String[] args)
- {
- SingletonTest st = SingletonTest.getInstance();
- SingletonTest st2 = SingletonTest.getInstance();
-
- System.out.println(st == st2);
- }
原文地址:https://www.cnblogs.com/hoobey/p/5294381.html