单例模式
什么是单例模式
- 一个类只能有一个实例
- 该类的实例由该类自己来创建
- 该类创建的实例必须提供给其他对象
饿汉式
public class Singelon {
private Singelon(){
System.out.println("创建了一个对象");
}
private static final Singelon single = new Singelon();
public static Singelon getInstance(){
return single;
}
public void Hello(){
System.out.println("Hello,world");
}
}
懒汉式
public class Singelon1 {
private Singelon1(){
System.out.println("创建了一个对象");
}
private static Singelon1 single1 = null;
public static Singelon1 getInstance(){
if(single1 == null){
single1 = new Singelon1();
}
return single1;
}
public void hello(){
System.out.println("hello,java");
}
}