1、单例模式
- 单例模式主要是为了避免因为创建了多个实例造成资源的浪费,且多个实例由于多次调用容易导致结果出现错误,而使用单例模式能够保证整个应用中有且只有一个实例。
- 恶汉模式实现
public class SingletonEHan {private SingletonEHan() {}private static SingletonEHan singletonEHan = new SingletonEHan();public static SingletonEHan getInstance() {return singletonEHan;}private static SingletonEHan singletonEHanTwo = null;static {singletonEHanTwo = new SingletonEHan();}public static SingletonEHan getSingletonEHan() {if (singletonEHanTwo == null) {singletonEHanTwo = new SingletonEHan();}return singletonEHanTwo;}
}
public class SingletonLanHan {private SingletonLanHan() {}private static SingletonLanHan singletonLanHan;public static SingletonLanHan getInstance() {if (singletonLanHan == null) { singletonLanHan = new SingletonLanHan();}return singletonLanHan;}private static SingletonLanHan singletonLanHanTwo;public static synchronized SingletonLanHan getSingletonLanHanTwo() {if (singletonLanHanTwo == null) { singletonLanHanTwo = new SingletonLanHan();}return singletonLanHanTwo;}private static SingletonLanHan instanceThree = null;public static SingletonLanHan getSingletonLanHanThree() {if (instanceThree == null) {synchronized (SingletonLanHan.class) {instanceThree = new SingletonLanHan();}}return instanceThree;}private static SingletonLanHan singletonLanHanFour;public static SingletonLanHan getSingletonLanHanFour() {if (singletonLanHanFour == null) {synchronized (SingletonLanHan.class) {if (singletonLanHanFour == null) {singletonLanHanFour = new SingletonLanHan();}}}return singletonLanHanFour;}
}
public class SingletonIn {private SingletonIn() {}private static class SingletonInHodler {private static SingletonIn singletonIn = new SingletonIn();}public static SingletonIn getSingletonIn() {return SingletonInHodler.singletonIn;}
}
public enum SingletonEnum {instance;private SingletonEnum() {}public void whateverMethod() {}}