单例模式
保证每个类只有一个实例,并提供一个全局访问点
第一步 构造方法私有化
第二步 公有化静态方法获取的实例
懒汉式
public class Bank{ private Bank(){} private static Bank bank = null; public static Bank getInstances(){ if(bank == null){ bank = new Bank(); } return bank; } }
构造方法在私有化之后在main方法中是不能创建对象的,也就不能用对象点方法
调用getInstances,所以getInstances方法要加static直接用Bank.getInstances.
在静态的方法中是不能有实例变量的,所以bank要加static
对于懒汉式有时候会造成线程安全问题,最好加synchronnized
public class Bank{ private Bank(){} private static Bank bank = null; public static synchronized Bank getInstances(){ if(bank == null){ bank = new Bank(); } return bank; } }
double check版本
public class Bank{ private Bank(){} private static Bank bank = null; public static Bank getInstances(){ if(bank == null){ synchronized(this){ if(bank == null){ bank = new Bank(); } } } return bank; } }
饿汉式
public class Bank{ private Bank(){} private static Bank bank = new Bank(); public static Bank getInstances(){ return bank; } }
内部类方式
public class SingleTon { private SingleTon() { } private static class SingleTonHolder { private static SingleTon instance = new SingleTon(); } public static SingleTon getInstance() { return SingleTonHolder.instance; } }
采用内部类方式维护单例,可以做到懒加载又可以做到不采用关键字synchronized,避免双重锁机制判断