單例模式的應用場景
當你需要有且僅有一個對象,供全局使用,比如讀取配置文件、數據庫連接池、線程池等等
為什么要單例模式
資源共享的情況下,避免由于資源操作時導致的性能或損耗等。如上述中的日志文件,應用配置。
控制資源的情況下,方便資源之間的互相通信。如線程池等。
java單例模式
- 餓漢模式
package singleton;
public class Hungry {
private static Hungry singleton = new Hungry(); // 類加載的時候 就創建了
private Hungry() {
}
public static Hungry getHungryInstance() {
return singleton;
}
}
- 懶漢模式
package singleton;
public class Lazy {
private Lazy() {
}
private static Lazy instance;
public static Lazy getLazyInstance() {
if (instance == null) {
instance = new Lazy();
}
return instance;
}
}
“餓漢”、“懶漢”區別
- 類加載時,對象是否創建;餓漢加載時較慢,創建了單例對象,使用對象時很快;懶漢反之
- 線程安全問題 餓漢是安全,懶漢不安全
網上找的一個讀取配置文件的小案例
package org.jediael.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class BasicConfiguration {
private Properties pros = null;
private static class ConfigurationHolder{
private static BasicConfiguration configuration = new BasicConfiguration();
}
public static BasicConfiguration getInstance(){
return ConfigurationHolder.configuration;
}
public String getValue(String key){
return pros.getProperty(key);
}
private BasicConfiguration(){
readConfig();
}
private void readConfig() {
pros = new Properties();
InputStream in = null;
try {
in = new FileInputStream(Thread.currentThread().getContextClassLoader().getResource("")
.getPath() + "search.properties");
pros.load(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}