单例模式:确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
package com.juno.SinglePattern;
// 饿汉式单例,通用代码,建议
public class SingletonOne {private static final SingletonOne instance = new SingletonOne();private SingletonOne() {}public static SingletonOne getInstance() {return instance;}public static void doSomething() {System.out.println("Singleton One do something~~");}
}
package com.juno.SinglePattern;
// 懒汉式单例
public class SingletonSecond {private static SingletonSecond instance = null;private SingletonSecond() {}public synchronized static SingletonSecond getInstance() {if (null == instance) {instance = new SingletonSecond();}return instance;}public static void doSomething() {System.out.println("Singleton Second do something~~");}
}
package com.juno.SinglePattern;public class Singleton {public static void main(String[] args) {SingletonOne singletonOne = SingletonOne.getInstance();SingletonSecond singletonSecond = SingletonSecond.getInstance();singletonOne.doSomething();singletonSecond.doSomething();}
}