/*
- 懒汉式单例模式的写法
- */
public class SinglePattern {
// 私有构造方法
private SinglePattern(){}
// 定义一个类变量用于接收该类对象
private static SinglePattern singlePatternDemo;
// 对外提供一个方法,并判断该类是否被创建过,如果没有就创建返回,如果已经创建过就直接返回
public static SinglePattern getInstance(){
if (singlePatternDemo==null){
//第一次创建
singlePatternDemo = new SinglePattern();
}
return singlePatternDemo;
}
}
/*
- 饿汉式单例模式
- */
public class SinglePatternOther {
//私有构造方法
private SinglePatternOther(){}
// 创建一个类变量接收当前类的类对象
private static SinglePatternOther singlePatternOtherDemo = new SinglePatternOther();
//对外提供一个方法将类对象返回
public static SinglePatternOther getInstant(){
return singlePatternOtherDemo;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(SinglePattern.getInstance());
System.out.println(SinglePattern.getInstance());
System.out.println(SinglePattern.getInstance());
System.out.println(SinglePattern.getInstance());
System.out.println(SinglePattern.getInstance());
System.out.println(SinglePatternOther.getInstant());
System.out.println(SinglePatternOther.getInstant());
System.out.println(SinglePatternOther.getInstant());
System.out.println(SinglePatternOther.getInstant());
System.out.println(SinglePatternOther.getInstant());
}
}
网友评论