单例模式 确保一个类只有一个实例,而且自行实例化并向系统提供这个实例。
Singleton Pattern Ensure a class has only one instance,and provide a global point of access to it.
Singleton类称为单例类,通常使用private的构造函数确保乐在一个应用中只产生一个实例,并且是自行实例化的(在Singleton中自己使用new Singleton())。
单例模式通用代码:
private class Singleton {
private static final Singleton singleton =new Singleton();
//限制产生多个对象
private Singleton (){
}
public static Singleton getSingleton(){
return singleton;
}
//orhers method
}
单例模式的优点
a)由于单例模式在内存中只有一个实例,减少了内存开支,特别是一个对象需要频繁的创建销毁时,而创建销毁时的性能又无法优化单例模式的性能非常明显。
单例模式的缺点
单例模式没有接口,扩展困难
单例模式是自行实例化的接口对单例模式没有任何意义接口或抽象是不可能被实例化的
单例模式与单一职则原则有冲突,一个类应该只能实现一个逻辑。
单例模式应用场景
要求生成唯一序列号的环境;
在整个项目中需要共享访问点或者共享数据。使用单例模式保持计数器的值,并确保线程是安全的;
创建一个对象需要消耗的资源过多 Eg访问IO 数据库
需要定义大量的静态常量和静态方法(工具类的环境)
单例模式注意事项
懒汉模式
public class Singleton {
private static Singleton singleton =null;
private Singleton(){
if(singleton==null){
singleton = new Singleton();
}
return singleton;
}
}
饿汉模式
在函数前加synchronized关键字
单例模式扩展
class Singleton{
private static int maxNumOfSingleton=2;//定义最多能产生的实例数
private static ArrayList <String> nameList = new ArrayList<String>();
private static ArrayList<Singleton> singleList = new ArralyList<Singleton>();
private static int countNumOfSingleton=0;static{
for(int i=0;i<maxNumOfSingleton;i++){
singleList.add(new Singleton());
}
}
private Singleton(){
}
private Singleton(String name){
namelist.add(name);
}
public static Singleton getInstance(){
Random random = new Random();
countNUmOfSingleton =random.nextInt(maxNumOfSingle);
return singletonList.get(countNumOfSingleton);
}
//orther method
}