单例模式,只提供一个实例,不能通过构造方法创建对象。
1、懒汉模式
public class TestDemo{
privata static TestDemo test;
/*
*将构造方法私有化,外部不能通过其创建对象
*/
private TestDemo(){
}
/*
*用static修饰可以通过类名直接调用
*/
public static TestDemo get(){
if(test==null){
test = new TestDemo();
}
return test;
}
}
2、饿汉模式,效率低。
public class TestDemo{
privata static TestDemo test = new TestDemo();
/*
*将构造方法私有化,外部不能通过其创建对象
*/
private TestDemo(){
}
/*
*用static修饰可以通过类名直接调用
*/
public static TestDemo get(){
return test;
}
}