//饿汉式单例
class Singleton{
//类内部提供实例化对象
private static final Singleton singleton=new Singleton();
//构造方法私有化,类外部无法产生实例化对象
private Singleton(){
}
public void test(){
System.out.println(this);
}
//对象方法
public static Singleton getSingleton(){
return singleton;
}
}
public class Test {
public static void main(String[] args) {
Singleton singleton= Singleton.getSingleton();
Singleton singleton1= Singleton.getSingleton();
Singleton singleton2 = Singleton.getSingleton();
singleton.test();
singleton1.test();
singleton2.test();
}
}
懒汉式单例:用时再new
class Singleton{
//
private static Singleton singleton;//为什么属性要用static修饰:类的对象与实例化无关
private Singleton()//为什么单例模式可以限制产生对象的个数:私有构造属性
{
}
public void test(){
System.out.println(this);
}
//对象方法
public static Singleton getSingleton(){
if(singleton == null){
singleton =new Singleton();
}
return singleton;
}
}
public class Test {
public static void main(String[] args) {
Singleton singleton= Singleton.getSingleton();
Singleton singleton1= Singleton.getSingleton();
Singleton singleton2 = Singleton.getSingleton();
singleton.test();
singleton1.test();
singleton2.test();
}
}