懒汉模式:
public class Test04 {
public static void main(String[] args) {Besom b1=Besom.getInstance();
b1.clean();
Besom b2=Besom.getInstance();
b2.clean();
}
}
/*
* 单例模式
* 单个实例,同一个唯一的实例
*/
class Besom{
//1 私有化构造器
private Besom(){}
//2 在本类中提供一个对该对象的引用
private static Besom besom;
//3 对外提供方法 访问该对象
public static Besom getInstance(){
if(besom!=null){
return besom;
}else{
besom = new Besom();
return besom;
}
}
public void clean(){
System.out.println("地址是"+this+"正在扫地");
}
}
恶汉模式
class Dustpan{
private Dustpan(){}
private static final Dustpan dustpan = new Dustpan();
public static Dustpan getInstance() {
return dustpan;
}
}