核心思想
保证单例模式只有一个实例的核心思想是构造方法私有化,单例模式可从3个属性评判:
- 单实例
- 懒加载
- 高性能
分类
饿汉式
public final class Singleton {
/**
* 实例变量
*/
private byte[] data = new byte[1024];
private static final Singleton instance = new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
}
饿汉式的关键在于instance作为类变量并且直接得到了初始化,只要使用到Singleton类,instance就会完成创建,实例变量都会得到初始化(如1K大小的data)。
饿汉模式是线程安全的,可以保证多线程下的唯一实例,getInstance方法的性能比较高。
如果一个类中的成员属性较少,且占用的内存资源不多,饿汉的方式未尝不可。
懒汉式
懒汉模式就是在使用类实例的时候再去创建(用时创建),避免类在初始化的时候提前创建。
public final class Singleton {
private byte[] data = new byte[1024];
private static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
if (instance == null){
instance = new Singleton();
}
return instance;
}
}
懒汉模式使非线程安全的,多个线程可能会同时判定instance == null,此时instance无法保证唯一性。
懒汉式+同步方法
懒汉式的方式可以保证实例的懒加载,但无法保证实例的唯一性,通过添加同步约束即可。
public final class Singleton {
private byte[] data = new byte[1024];
private static final Singleton instance = new Singleton();
private Singleton(){
}
public static synchronized Singleton getInstance(){
return instance;
}
}
懒汉式+数据同步的方式既满足了懒加载又能保证instance实例的唯一性。但是synchronized关键字的排他性导致getInstance方法只能在同一时刻被一个线程访问,性能低下。
Holder方式(☆)
Holder方式的单例设计是最好的设计之一,同时满足了单实例、懒加载、高性能。
public final class Singleton {
private byte[] data = new byte[1024];
private Singleton(){}
private static class Holder{
private static Singleton instance = new Singleton();
}
public static Singleton getInstance(){
return Holder.instance;
}
}
Holder方式借助了类加载的特点。
在Singleton类中没有instance的静态成员,而是将其放到了静态内部类Holder之中,因此在Singleton类的初始化过程中不会创建Singleton的实例,Holder类中定义了Singleton的静态变量,并且直接进行了实例化。当Holder被主动引用的时候会创建Singleton的实例。
Singleton实例的创建过程在Java程序编译时期收集至()方法中,该方法又是同步方法。
其他单例模式
- 枚举方式
- Double-Check
应用示例
编辑日志类
一般来说,应用程序都有日志文件,记录一些执行信息,该功能利用单例对象来实现比较合适。
public class FileLogger {
private String path = "E:\\WorkStations\\IdeaProjects\\DesignPattern\\src\\chapter2\\demo5\\log.txt";
private FileOutputStream out;
private FileLogger() throws Exception {
out = new FileOutputStream(path, true);
System.out.println("This is a new instance!");
}
public void write(String msg) {
try {
Calendar calendar = Calendar.getInstance();
int y = calendar.get(Calendar.YEAR);
int m = calendar.get(Calendar.MONTH);
int d = calendar.get(Calendar.DAY_OF_MONTH);
int hh = calendar.get(Calendar.HOUR);
int mm = calendar.get(Calendar.MINUTE);
int ss = calendar.get(Calendar.SECOND);
String strTime = "";
strTime = String.format("time:%d-%02d-%02d %02d:%02d:%02d\r\n", y, m, d, hh, mm, ss);
String strContent = strTime + "content:" + msg + "\r\n";
byte[] buf = strContent.getBytes("utf8");
out.write(buf);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static class Holder {
private static FileLogger logger;
static {
try {
logger = new FileLogger();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static FileLogger getInstance() {
return Holder.logger;
}
}
本例中日志单例是利用Holder方式实现的,Holder使用静态代码块是由于FileLogger的构造函数会抛出异常。
public class Test {
public static void main(String[] args) {
FileLogger logger = FileLogger.getInstance();
logger.write("hello");
logger.write("你好!");
logger.close();
}
}
编辑配置文件信息
配置文件是应用程序经常采用的技术,它的内容为整个应用程序所共享,具有唯一性。假设数据库文件的信息如下:
url=jdbc:mysql://localhost:3306/mydb
username=root
password=123456
读取配置文件单例类的设计如下:
public final class Config {
private Map<String,String> map = new HashMap<>();
private Config() throws Exception{
FileInputStream in = new FileInputStream("E:\\WorkStations\\IdeaProjects\\DesignPattern\\src\\demo6\\config.properties");
Properties p = new Properties();
p.load(in);
for (Entry<Object,Object> entry : p.entrySet()){
String key = (String) entry.getKey();
String value = (String) entry.getValue();
map.put(key,value);
}
}
private static class Holder{
private static Config instance;
static {
try {
instance = new Config();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static Config getInstance(){
return Holder.instance;
}
public String getInfo(String key){
return map.get(key);
}
}
public class Test {
public static void main(String[] args) {
Config config = Config.getInstance();
String url = config.getInfo("url");
String user = config.getInfo("username");
String pwd = config.getInfo("password");
System.out.println("url="+url);
System.out.println("user="+user);
System.out.println("pwd="+pwd);
}
}
Servlet映射仿真
为了提高应用服务器的运行效率,许多类对象都是单例的。例如Web编程中的JSP、Servlet等在内存中只有一个实例。
若JSP、Servlet等不是单例,当大量用户访问页面的时候,就会产生大量对象,导致服务器崩溃。
以Servlet为例,每创建一个Servlet,在web.xml中就生成一对Servlet标签,如:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>mypack.Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
以下仿真这一过程:
配置文件config.properties,plusurl是特征串,plus是name值,chapter2.demo7.PlusFunc表示具体的类。
plusurl=plus,chapter2.demo7.PlusFunc
minusurl=minus,chapter2.demo7.MinusFunc
接口与功能类
public interface Func {
int service(int one,int two);
}
public class PlusFunc implements Func {
private PlusFunc() {
}
private static class Holder {
private static final PlusFunc instance = new PlusFunc();
}
public static PlusFunc getInstance() {
return Holder.instance;
}
@Override
public int service(int one, int two) {
return one + two;
}
}
public class MinusFunc implements Func {
private MinusFunc() {
}
private static class Holder {
private static final MinusFunc instance = new MinusFunc();
}
public static MinusFunc getInstance() {
return Holder.instance;
}
@Override
public int service(int one, int two) {
return one - two;
}
}
维护类
public class Integrate {
private static Map<String, String> mapUrlToName = new HashMap<>(16);
private static Map<String, String> mapNameToClass = new HashMap<>(16);
private static Map<String, Func> mapPhysicasClass = new HashMap<>(16);
public static void init() {
try {
FileInputStream in = new FileInputStream("E:\\WorkStations\\IdeaProjects\\DesignPattern\\src\\chapter2\\demo7\\config.properties");
Properties p = new Properties();
p.load(in);
for (Entry<Object, Object> entry : p.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
String[] unit = value.split(",");
String url = key;
String name = unit[0];
String className = unit[1];
mapUrlToName.put(url, name);
mapNameToClass.put(name, className);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void run() throws Exception {
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("Please input url:");
String strUrls = s.nextLine();
String[] unit = strUrls.split(" ");
String url = unit[0];
int one = Integer.parseInt(unit[1]);
int two = Integer.parseInt(unit[2]);
String name = mapUrlToName.get(url);
Func obj = mapPhysicasClass.get(name);
if (obj == null) {
String className = mapNameToClass.get(name);
Class c = Class.forName(className);
Method m = c.getDeclaredMethod("getInstance");
obj = (Func) m.invoke(null);
mapPhysicasClass.put(name, obj);
}
int result = obj.service(one, two);
System.out.println("The result is:" + result);
}
}
public static void main(String[] args) throws Exception{
Integrate.init();
Integrate.run();
}
}