写出几种单例模式
懒汉式-静态内部类
public class test {
/**
私有改造方法
**/
private test(){
}
/**
内部静态类
**/
private static class testTwo{
private static final test testOne=new test();
}
public static test getTest(){
return testTwo.testOne;
}
}
懒汉式-双重检查
public class test{
private test(){
}
private static volatile test testOne;
public static test getTest(){
if(testOne == null){
synchronized(test.class){
if(testOne == null){
testOne=new test();
}
}
}
return testOne;
}
}
饿汉式-静态变量
public class test{
private test(){}
private static test testOne=new test();
public static test getTest(){
return testOne;
}
}
饿汉式-静态代码块
public class test{
private test(){}
private static test testOne;
static{
testOne =new test()
}
public static test getTest(){
return testOne;
}
}
饿汉式-枚举
public enum test{
testOne;
}
本文详细介绍了五种不同的单例模式实现方法,包括懒汉式的静态内部类和双重检查方式,以及饿汉式的静态变量、静态代码块和枚举方式。每种实现都有其特点和适用场景。
1983

被折叠的 条评论
为什么被折叠?



