Java设计模式-单例模式

xiaoxiao2021-02-28  23

一、懒汉模式

public class LazySingleton { /** *  * 构造函数私有化 */ //懒汉模式 private LazySingleton() { } private static LazySingleton singleton; public static LazySingleton getInstance() { if (singleton == null) { return new LazySingleton(); } return singleton; }

二、饿汉模式

public class HungrySingleton { //饿汉模式-加载慢,运行快,线程安全 //单例模式Sinletion /** *  * 构造函数私有化 */ private HungrySingleton() { } private static HungrySingleton hungrySingleton = new HungrySingleton(); public static HungrySingleton getInstance() { return hungrySingleton; } }

 

转载请注明原文地址: https://www.6miu.com/read-1650214.html

最新回复(0)