package com.yunhe.designpattern;
//饿汉式单例设计模式
class Singleton{
//直接创建一个对象 编译时就生成了一个实例
private final static Singleton INSTANCE=new Singleton();
private Singleton(){};
public static Singleton getSingleton() {
return INSTANCE;
}
public void show() {
System.out.println("饿汉式单例");
}
}
//懒汉式单例设计模式
class LSingleton{
private static LSingleton INSTANCE;
private LSingleton() {}
public static LSingleton getLSingleton() {
//判断当前有没有对象 没有则创建,有则直接返回
if(INSTANCE==null) {
INSTANCE=new LSingleton();
}
return INSTANCE;
}
public void show() {
System.out.println("懒汉式单例");
}
}
public class SingletonTest{
public static void main(String[] args) {
Singleton singleton= Singleton.getSingleton();
singleton.show();
LSingleton lSingleton=LSingleton.getLSingleton();
lSingleton.show();
}
}
设计模式------单例设计模式
最新推荐文章于 2024-07-14 13:56:18 发布