单例模式
单例模式:一个类只产生一个实例化对象
如何限制对象的产生数量?
-
private声明构造方法(无对象)
-
单例类内部提供一个产生好的对象
-
单例类内部提供静态方法返回唯一的一个对象
饿汉式单例:
class Test{ private static final Test test=new Test(); private Test(){} public static Test getInstance(){ return test; } } public class SingletonTest { public static void main(String[] args) { Test test = null ; // 声明对象 test = Test.getInstance() ; } }
饿汉式单例上来就new,懒汉式单例用时在new。写就写饿汉式单例,懒汉式单例存在线程安全问题(双重加锁单例模式)。
懒汉式单例:
package test;
class Singleton{
private static Singleton instance ;
private Singleton() { // private声明构造
}
public static Singleton getInstance() {
if (instance==null) { // 表示此时还没有实例化
instance = new Singleton() ;
}
return instance ;
}
public void print() {
System.out.println("Hello");
}
}
public class SingletonTest {
public static void main(String[] args) {
Singleton singleton = null ; // 声明对象
singleton = Singleton.getInstance() ;
singleton.print();
}
}
单例程序特点:构造方法私有化,外部无法产生新的实例化对象,只能通过static方法取得实例化对象。
多例模式:一个类的对象数量是有限个–枚举