singleton
单例模式,是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中,应用该模式的类一个类只有一个实例。即一个类只有一个对象实例。
为什么要用单例模式
在实际的项目中,有一些东西是大家共用的,比如:系统配置、redis实例、数据库实例等,我们不希望每个用户在使用这些资源的时候,自己去新建一份实例,这样会造成资源的浪费。
目的:保证一个类只有一个实例
使用场景:当你想控制实例个数,节省系统资源的时候
解决方案:判断该类是否已经有实例,如果有则返回,没有则创建
关键代码:私有化构造函数,让使用方不能随意的去实例
实现方案:懒汉、饿汉、静态内部类、枚举
懒汉 - 线程不安全
package com.my.test.singleton;
//懒汉 - 线程不安全
public class SingletonExample01 {
private SingletonExample01(){
}
private static SingletonExample01 instance = null;
public static SingletonExample01 getInstance(){
if(instance == null){
instance = new SingletonExample01();
}
return instance;
}
}
懒汉 - 线程安全
package com.my.test.singleton;
//懒汉 - 线程安全
public class SingletonExample02 {
private SingletonExample02(){
}
private static SingletonExample02 instance = null;
public static synchronized SingletonExample02 getInstance(){
if(instance == null){
instance = new SingletonExample02();
}
return instance;
}
}
双重校验锁
package com.my.test.singleton;
//懒汉 - 双重校验锁
public class SingletonExample03 {
private SingletonExample03(){
}
private static volatile SingletonExample03 instance = null;
public static SingletonExample03 getInstance(){
if(instance == null){
synchronized (SingletonExample03.class){
if(instance == null){
instance = new SingletonExample03();
}
}
}
return instance;
}
}
饿汉模式
package com.my.test.singleton;
//饿汉模式
public class SingletonExample04 {
private SingletonExample04(){
}
// 方法一
// private static SingletonExample04 instance = new SingletonExample04();
// 方法二
private static SingletonExample04 instance = null;
static {
instance = new SingletonExample04();
}
public static SingletonExample04 getInstance(){
return instance;
}
}
静态内部类
package com.my.test.singleton;
// 静态内部类
public class SingletonExample05 {
private SingletonExample05(){
}
private static class InstanceSingletonExample05{
private static SingletonExample05 instance = new SingletonExample05();
}
public static SingletonExample05 getInstance(){
return InstanceSingletonExample05.instance;
}
}
枚举
package com.my.test.singleton;
// 枚举
public class SingletonExample06 {
private SingletonExample06(){
}
public static SingletonExample06 getInstance(){
return InstanceSingletonExample06.INSTANCE.getSingletonExample06();
}
private enum InstanceSingletonExample06{
INSTANCE;
private SingletonExample06 singletonExample06 = new SingletonExample06();
public SingletonExample06 getSingletonExample06(){
return singletonExample06;
}
}
}
枚举2.0
package com.my.test.singleton;
public enum SingletonEnumExample{
INSTANCE;
public void test(){
// do everything
}
}
实例场景之 - 获取jdbc连接
我们新增两个类,第一个是非单例的获取jdbc连接
package com.mk.designDemo.singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MDataSourceNoSingle {
private static final Logger logger = LoggerFactory.getLogger(MDataSourceNoSingle.class);
private static Connection connection = null;
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://******:3306/*****?characterEncoding=UTF-8", "root", "root");
logger.info("线程{}实例化connection", Thread.currentThread().getName());
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return connection;
}
}
第二个使用了单例模式
package com.mk.designDemo.singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MDataSourceSingle {
private static final Logger logger = LoggerFactory.getLogger(MDataSourceSingle.class);
private static Connection connection = null;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://******:3306/*****?characterEncoding=UTF-8", "root", "root");
logger.info("线程{}实例化connection", Thread.currentThread().getName());
} catch (ClassNotFoundException | SQLException e) {
logger.error(e.getMessage(), e);
}
}
private MDataSourceSingle() {
}
public static Connection getConnection() {
return connection;
}
}
然后我们写了一个简单的controller,里面有两个接口,用来验证结果
package com.mk.designDemo.controller;
import com.mk.designDemo.singleton.MDataSourceNoSingle;
import com.mk.designDemo.singleton.MDataSourceSingle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Connection;
@RestController
public class SingletonController {
private static final Logger logger = LoggerFactory.getLogger(SingletonController.class);
private final static String sql = "select * from t_trade_date limit 10";
@RequestMapping(path = "/noSingleton")
public String noSingleton() {
MDataSourceNoSingle mDataSourceNoSingle = new MDataSourceNoSingle();
Connection connection = mDataSourceNoSingle.getConnection();
doExecute(connection, sql);
return "OK";
}
@RequestMapping(path = "/singleton")
public String singleton() {
doExecute(MDataSourceSingle.getConnection(), sql);
return "OK";
}
private void doExecute(Connection connection, String sql) {
logger.info("do execute sql:{}", sql);
}
}
当我们调用三次非单例的接口时,查看日志输出如下,connection被实例化了多次:
2019-07-09 15:47:31.966 [http-nio-80-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - GET "/web/noSingleton", parameters={}
2019-07-09 15:47:31.970 [http-nio-80-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped to public java.lang.String com.mk.designDemo.controller.SingletonController.noSingleton()
2019-07-09 15:47:32.633 [http-nio-80-exec-1] INFO c.m.d.singleton.MDataSourceNoSingle - 线程http-nio-80-exec-1实例化connection
2019-07-09 15:47:32.633 [http-nio-80-exec-1] INFO c.m.d.controller.SingletonController - do execute sql:select * from t_trade_date limit 10
2019-07-09 15:47:32.671 [http-nio-80-exec-1] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Using 'text/html', given [text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, */*;q=0.8] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-07-09 15:47:32.672 [http-nio-80-exec-1] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Writing ["OK"]
2019-07-09 15:47:32.693 [http-nio-80-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Completed 200 OK
2019-07-09 15:47:40.005 [http-nio-80-exec-4] DEBUG o.s.web.servlet.DispatcherServlet - GET "/web/noSingleton", parameters={}
2019-07-09 15:47:40.007 [http-nio-80-exec-4] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped to public java.lang.String com.mk.designDemo.controller.SingletonController.noSingleton()
2019-07-09 15:47:40.361 [http-nio-80-exec-4] INFO c.m.d.singleton.MDataSourceNoSingle - 线程http-nio-80-exec-4实例化connection
2019-07-09 15:47:40.361 [http-nio-80-exec-4] INFO c.m.d.controller.SingletonController - do execute sql:select * from t_trade_date limit 10
2019-07-09 15:47:40.362 [http-nio-80-exec-4] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Using 'text/html', given [text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, */*;q=0.8] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-07-09 15:47:40.362 [http-nio-80-exec-4] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Writing ["OK"]
2019-07-09 15:47:40.363 [http-nio-80-exec-4] DEBUG o.s.web.servlet.DispatcherServlet - Completed 200 OK
2019-07-09 15:47:48.459 [http-nio-80-exec-7] DEBUG o.s.web.servlet.DispatcherServlet - GET "/web/noSingleton", parameters={}
2019-07-09 15:47:48.461 [http-nio-80-exec-7] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped to public java.lang.String com.mk.designDemo.controller.SingletonController.noSingleton()
2019-07-09 15:47:48.801 [http-nio-80-exec-7] INFO c.m.d.singleton.MDataSourceNoSingle - 线程http-nio-80-exec-7实例化connection
2019-07-09 15:47:48.801 [http-nio-80-exec-7] INFO c.m.d.controller.SingletonController - do execute sql:select * from t_trade_date limit 10
2019-07-09 15:47:48.802 [http-nio-80-exec-7] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Using 'text/html', given [text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, */*;q=0.8] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-07-09 15:47:48.802 [http-nio-80-exec-7] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Writing ["OK"]
2019-07-09 15:47:48.803 [http-nio-80-exec-7] DEBUG o.s.web.servlet.DispatcherServlet - Completed 200 OK
然后我们调用单例的接口三次,日志输出如下,我们可以看到,只有第一次进行了实例化,后面再也没有继续实例化
2019-07-09 15:49:22.868 [http-nio-80-exec-10] DEBUG o.s.web.servlet.DispatcherServlet - GET "/web/singleton", parameters={}
2019-07-09 15:49:22.871 [http-nio-80-exec-10] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped to public java.lang.String com.mk.designDemo.controller.SingletonController.singleton()
2019-07-09 15:49:23.234 [http-nio-80-exec-10] INFO c.m.d.singleton.MDataSourceSingle - 线程http-nio-80-exec-10实例化connection
2019-07-09 15:49:23.235 [http-nio-80-exec-10] INFO c.m.d.controller.SingletonController - do execute sql:select * from t_trade_date limit 10
2019-07-09 15:49:23.237 [http-nio-80-exec-10] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Using 'text/html', given [text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, */*;q=0.8] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-07-09 15:49:23.237 [http-nio-80-exec-10] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Writing ["OK"]
2019-07-09 15:49:23.239 [http-nio-80-exec-10] DEBUG o.s.web.servlet.DispatcherServlet - Completed 200 OK
2019-07-09 15:49:25.032 [http-nio-80-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - GET "/web/singleton", parameters={}
2019-07-09 15:49:25.034 [http-nio-80-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped to public java.lang.String com.mk.designDemo.controller.SingletonController.singleton()
2019-07-09 15:49:25.034 [http-nio-80-exec-1] INFO c.m.d.controller.SingletonController - do execute sql:select * from t_trade_date limit 10
2019-07-09 15:49:25.035 [http-nio-80-exec-1] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Using 'text/html', given [text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, */*;q=0.8] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-07-09 15:49:25.036 [http-nio-80-exec-1] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Writing ["OK"]
2019-07-09 15:49:25.038 [http-nio-80-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Completed 200 OK
2019-07-09 15:49:25.926 [http-nio-80-exec-2] DEBUG o.s.web.servlet.DispatcherServlet - GET "/web/singleton", parameters={}
2019-07-09 15:49:25.926 [http-nio-80-exec-2] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped to public java.lang.String com.mk.designDemo.controller.SingletonController.singleton()
2019-07-09 15:49:25.927 [http-nio-80-exec-2] INFO c.m.d.controller.SingletonController - do execute sql:select * from t_trade_date limit 10
2019-07-09 15:49:25.928 [http-nio-80-exec-2] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Using 'text/html', given [text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, */*;q=0.8] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-07-09 15:49:25.928 [http-nio-80-exec-2] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Writing ["OK"]
2019-07-09 15:49:25.929 [http-nio-80-exec-2] DEBUG o.s.web.servlet.DispatcherServlet - Completed 200 OK
验证通过,OVER!