java中單例模式是一種常見的設(shè)計(jì)模式,單例模式分三種:懶漢式單例、餓漢式單例、登記式單例三種。
成都創(chuàng)新互聯(lián)主營鐘祥網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,app軟件開發(fā),鐘祥h5微信小程序開發(fā)搭建,鐘祥網(wǎng)站營銷推廣歡迎鐘祥等地區(qū)企業(yè)咨詢
單例模式有一下特點(diǎn):
1、單例類只能有一個(gè)實(shí)例。
2、單例類必須自己自己創(chuàng)建自己的唯一實(shí)例。
3、單例類必須給所有其他對象提供這一實(shí)例。
單例模式確保某個(gè)類只有一個(gè)實(shí)例,而且自行實(shí)例化并向整個(gè)系統(tǒng)提供這個(gè)實(shí)例。在計(jì)算機(jī)系統(tǒng)中,線程池、緩存、日志對象、對話框、打印機(jī)、顯卡的驅(qū)動(dòng)程序?qū)ο蟪1辉O(shè)計(jì)成單例。這些應(yīng)用都或多或少具有資源管理器的功能。每臺計(jì)算機(jī)可以有若干個(gè)打印機(jī),但只能有一個(gè)Printer Spooler,以避免兩個(gè)打印作業(yè)同時(shí)輸出到打印機(jī)中。每臺計(jì)算機(jī)可以有若干通信端口,系統(tǒng)應(yīng)當(dāng)集中管理這些通信端口,以避免一個(gè)通信端口同時(shí)被兩個(gè)請求同時(shí)調(diào)用??傊?,選擇單例模式就是為了避免不一致狀態(tài),避免政出多頭。
首先看一個(gè)經(jīng)典的單例實(shí)現(xiàn)。
public class Singleton {
private static Singleton uniqueInstance = null;
private Singleton() {
// Exists only to defeat instantiation.
}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// Other methods...
}
Singleton通過將構(gòu)造方法限定為private避免了類在外部被實(shí)例化,在同一個(gè)虛擬機(jī)范圍內(nèi),Singleton的唯一實(shí)例只能通過getInstance()方法訪問。(事實(shí)上,通過Java反射機(jī)制是能夠?qū)嵗瘶?gòu)造方法為private的類的,那基本上會使所有的Java單例實(shí)現(xiàn)失效。此問題在此處不做討論,姑且掩耳盜鈴地認(rèn)為反射機(jī)制不存在。)
但是以上實(shí)現(xiàn)沒有考慮線程安全問題。所謂線程安全是指:如果你的代碼所在的進(jìn)程中有多個(gè)線程在同時(shí)運(yùn)行,而這些線程可能會同時(shí)運(yùn)行這段代碼。如果每次運(yùn)行結(jié)果和單線程運(yùn)行的結(jié)果是一樣的,而且其他的變量的值也和預(yù)期的是一樣的,就是線程安全的。或者說:一個(gè)類或者程序所提供的接口對于線程來說是原子操作或者多個(gè)線程之間的切換不會導(dǎo)致該接口的執(zhí)行結(jié)果存在二義性,也就是說我們不用考慮同步的問題。顯然以上實(shí)現(xiàn)并不滿足線程安全的要求,在并發(fā)環(huán)境下很可能出現(xiàn)多個(gè)Singleton實(shí)例。
//////////////////////////////////////////////////////////////////////
驗(yàn)證單例模式的示例
//////////////////////////////////////////////////////////////////////
public class TestStream {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 該類只能有一個(gè)實(shí)例
private TestStream() {
} // 私有無參構(gòu)造方法
// 該類必須自行創(chuàng)建
// 有2種方式
private static TestStream ts1 = null;
// 這個(gè)類必須自動(dòng)向整個(gè)系統(tǒng)提供這個(gè)實(shí)例對象
public static TestStream getTest() {
if (ts1 == null) {
ts1 = new TestStream();
}
return ts1;
}
public void getInfo() {
System.out.println("output message " + name);
}
public static void main(String[] args) {
TestStream s = TestStream.getTest();
s.setName("張孝祥 1");
System.out.println(s.getName());
TestStream s1 = TestStream.getTest();
s1.setName("張孝祥 2");
System.out.println(s1.getName());
s.getInfo();
s1.getInfo();
if (s == s1) {
System.out.println("創(chuàng)建的是同一個(gè)實(shí)例");
} else if (s != s1) {
System.out.println("創(chuàng)建的不是同一個(gè)實(shí)例");
} else {
System.out.println("application error");
}
}
}
////////////////////////////////////////////
單例模式(Singleton) ,屬于最常見的設(shè)計(jì)模式之一,大部分系統(tǒng)都會用到,目的是為了維護(hù)系統(tǒng)中唯一的一個(gè)實(shí)例。
可分為eager模式,示例代碼如下:
Java代碼
1.class EagerSingleton{
2. private static final EagerSingleton m_instance = new EagerSingleton();
3. private EagerSingleton(){}
4. public static EagerSingleton getInstance(){
5. return m_instance;
6. }
7.}
class EagerSingleton{
private static final EagerSingleton m_instance = new EagerSingleton();
private EagerSingleton(){}
public static EagerSingleton getInstance(){
return m_instance;
}
}
和 lazy模式,示例代碼如下:
Java代碼
1.class LazySingleton{
2. private static LazySingleton m_instance = null;
3. private LazySingleton(){}
4. public synchronized static getInstance(){
5. if(m_instance == null){
6. m_instance = new LazySingleton();
7. }
8. return m_instance;
9. }
10.}
class LazySingleton{
private static LazySingleton m_instance = null;
private LazySingleton(){}
public synchronized static getInstance(){
if(m_instance == null){
m_instance = new LazySingleton();
}
return m_instance;
}
}
java源碼中,Runtime.getRuntime()就是單例的一個(gè)例子。
單例模式的精神就是整個(gè)系統(tǒng)中維護(hù)一個(gè)實(shí)例,推廣開來,如果在一個(gè)系統(tǒng)中需要維護(hù)多個(gè)示例,那么就產(chǎn)生了多例模式(multiton)。
多例模式(Multiton) ,通過聚集對象了保留自身的多個(gè)示例,根據(jù)客戶端的參數(shù)返回所需要的實(shí)例。
示例代碼如下:
Java代碼
1.class Multiton{
2. private final int INSTANCE_SIZE = 10;
3. private static Map instances = new HashMap(INSTANCE_SIZE);
4. private String name;
5. private Multiton(){}
6. private Multiton(String name){
7. this.name = name;
8. }
9. public synchronized static getInstance(String name){
10. if(instances.containsKey(name)){
11. return instances.get(name);
12. }
13. else{
14. ins = new Multiton(name);
15. instances.put(name, ins);
16. return ins;
17. }
18. }
19.}
class Multiton{
private final int INSTANCE_SIZE = 10;
private static Map instances = new HashMap(INSTANCE_SIZE);
private String name;
private Multiton(){}
private Multiton(String name){
this.name = name;
}
public synchronized static getInstance(String name){
if(instances.containsKey(name)){
return instances.get(name);
}
else{
ins = new Multiton(name);
instances.put(name, ins);
return ins;
}
}
}
[nextpage]
一個(gè)實(shí)用的例子就是KeyGenerator, 示例代碼如下:
Java代碼
1.class KeyGenerator{
2. private final int POOL_SIZE = 20;
3. private static Map instances = new HashMap(16);
4. private KeyInfo keyinfo;
5. private KeyGenerator(){}
6. private KeyGenerator(String keyName){
7. this.keyinfo = new KeyInfo(POOL_SIZE, keyName);
8. }
9. public synchronized static getInstance(String keyName){
10. if(instances.containsKey(keyName)){
11. return (KeyGenerator)instances.get(keyName);
12. }
13. else{
14. keyGen = new KeyGenerator(keyName);
15. instances.put(name, keyGen);
16. return keyGen;
17. }
18. }
19. public synzhronized int getNextKey(){
20. return keyinfo.getNextKey();
21. }
22. }
class KeyGenerator{
private final int POOL_SIZE = 20;
private static Map instances = new HashMap(16);
private KeyInfo keyinfo;
private KeyGenerator(){}
private KeyGenerator(String keyName){
this.keyinfo = new KeyInfo(POOL_SIZE, keyName);
}
public synchronized static getInstance(String keyName){
if(instances.containsKey(keyName)){
return (KeyGenerator)instances.get(keyName);
}
else{
keyGen = new KeyGenerator(keyName);
instances.put(name, keyGen);
return keyGen;
}
}
public synzhronized int getNextKey(){
return keyinfo.getNextKey();
}
}
創(chuàng)建一個(gè)名字為“ReportCard”的類,然后用下邊的內(nèi)容全部替換掉,你會成為全班最亮的仔。
import java.util.HashMap;
/**
* 學(xué)生成績單
*/
public class ReportCard {
public static void main(String[] args) {
ReportCard reportCard = new ReportCard("張三", "070602213");
reportCard.set("語文", 80.0);
reportCard.set("數(shù)學(xué)", 59.5);
reportCard.set("英語", 66.0);
reportCard.set("java", 80, 99.0);
reportCard.set("數(shù)據(jù)庫", 80, 66.0);
reportCard.set("毛概", null);
System.out.println(reportCard.getStudentName() + "語文分?jǐn)?shù):" + reportCard.get("語文"));
System.out.println(reportCard.getStudentName() + "數(shù)學(xué)考核結(jié)果:" + (reportCard.isPassed("數(shù)學(xué)") ? "合格" : "不合格"));
System.out.println(reportCard.getStudentName() + "期末是否掛科:" + (reportCard.isAllPassed() ? "否" : "是"));
}
// 學(xué)生姓名
private String studentName;
// 學(xué)生學(xué)號
private String studentNumber;
// 成績單
private HashMapString, CourseResult cards = new HashMap();
public ReportCard() {
}
public ReportCard(String studentName, String studentNumber) {
this.studentName = studentName;
this.studentNumber = studentNumber;
}
public Double get(String courseName){
CourseResult courseResult = cards.get(courseName);
return courseResult == null ? Double.NaN : courseResult.getStudentScore();
}
public void set(String courseName, Double studentScore){
CourseResult courseResult = new CourseResult(courseName, studentScore);
cards.put(courseName, courseResult);
}
public void set(String courseName, double passMark, Double studentScore){
CourseResult courseResult = new CourseResult(courseName, passMark, studentScore);
cards.put(courseName, courseResult);
}
public boolean isPassed(String courseName){
return cards.get(courseName).isPassed();
}
public boolean isAllPassed(){
for(CourseResult cr : cards.values()){
if ( ! cr.isPassed()) {
return false;
}
}
return true;
}
public String getStudentName() {
return studentName;
}
public String getStudentNumber() {
return studentNumber;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
/**
* 課程
*/
class Course{
// 課程名稱
protected String courseName;
// 及格分
protected double passMark = 60;
public Course(String courseName, Double passMark) {
this.courseName = courseName;
if ( passMark != null) {
this.passMark = passMark;
}
}
}
/**
* 課程成績
*/
class CourseResult extends Course{
// 學(xué)生成績
private Double studentScore;
public CourseResult(String courseName, Double studentScore) {
this(courseName, null, studentScore);
}
public CourseResult(String courseName, Double passMark, Double studentScore) {
super(courseName, passMark);
this.studentScore = studentScore == null ? Double.NaN : studentScore;
}
public boolean isPassed(){
return studentScore = passMark;
}
public String getCourseName() {
return courseName;
}
public double getPassMark() {
return passMark;
}
public Double getStudentScore() {
return studentScore;
}
}
一、懶漢式單例\x0d\x0a在類加載的時(shí)候不創(chuàng)建單例實(shí)例。只有在第一次請求實(shí)例的時(shí)候的時(shí)候創(chuàng)建,并且只在第一次創(chuàng)建后,以后不再創(chuàng)建該類的實(shí)例。\x0d\x0a \x0d\x0apublic class LazySingleton {\x0d\x0a /**\x0d\x0a * 私有靜態(tài)對象,加載時(shí)候不做初始化\x0d\x0a */\x0d\x0a private static LazySingleton m_intance=null;\x0d\x0a /**\x0d\x0a * 私有構(gòu)造方法,避免外部創(chuàng)建實(shí)例\x0d\x0a */\x0d\x0a private LazySingleton(){\x0d\x0a }\x0d\x0a /**\x0d\x0a * 靜態(tài)工廠方法,返回此類的唯一實(shí)例. \x0d\x0a * 當(dāng)發(fā)現(xiàn)實(shí)例沒有初始化的時(shí)候,才初始化.\x0d\x0a */\x0d\x0a synchronized public static LazySingleton getInstance(){\x0d\x0a if(m_intance==null){\x0d\x0a m_intance=new LazySingleton();\x0d\x0a }\x0d\x0a return m_intance;\x0d\x0a }\x0d\x0a}\x0d\x0a\x0d\x0a二、餓漢式單例\x0d\x0a在類被加載的時(shí)候,唯一實(shí)例已經(jīng)被創(chuàng)建。\x0d\x0a \x0d\x0apublic class EagerSingleton {\x0d\x0a /**\x0d\x0a * 私有的(private)唯一(static final)實(shí)例成員,在類加載的時(shí)候就創(chuàng)建好了單例對象\x0d\x0a */\x0d\x0a private static final EagerSingleton m_instance = new EagerSingleton();\x0d\x0a /**\x0d\x0a * 私有構(gòu)造方法,避免外部創(chuàng)建實(shí)例\x0d\x0a */\x0d\x0a private EagerSingleton() {\x0d\x0a }\x0d\x0a /**\x0d\x0a * 靜態(tài)工廠方法,返回此類的唯一實(shí)例.\x0d\x0a * @return EagerSingleton\x0d\x0a */\x0d\x0a public static EagerSingleton getInstance() {\x0d\x0a return m_instance;\x0d\x0a }\x0d\x0a}\x0d\x0a \x0d\x0a************************************************************************************** 懶漢方式,指全局的單例實(shí)例在第一次被使用時(shí)構(gòu)建; \x0d\x0a餓漢方式,指全局的單例實(shí)例在類裝載時(shí)構(gòu)建 \x0d\x0a**************************************************************************************\x0d\x0a\x0d\x0a三、登記式單例\x0d\x0a這個(gè)單例實(shí)際上維護(hù)的是一組單例類的實(shí)例,將這些實(shí)例存放在一個(gè)Map(登記薄)中,對于已經(jīng)登記過的實(shí)例,則從工廠直接返回,對于沒有登記的,則先登記,而后返回。\x0d\x0apublic class RegSingleton {\x0d\x0a /**\x0d\x0a * 登記薄,用來存放所有登記的實(shí)例\x0d\x0a */\x0d\x0a private static Map m_registry = new HashMap();\x0d\x0a //在類加載的時(shí)候添加一個(gè)實(shí)例到登記薄\x0d\x0a static {\x0d\x0a RegSingleton x = new RegSingleton();\x0d\x0a m_registry.put(x.getClass().getName(), x);\x0d\x0a }\x0d\x0a /**\x0d\x0a * 受保護(hù)的默認(rèn)構(gòu)造方法\x0d\x0a */\x0d\x0a protected RegSingleton() {\x0d\x0a }\x0d\x0a /**\x0d\x0a * 靜態(tài)工廠方法,返回指定登記對象的唯一實(shí)例;\x0d\x0a * 對于已登記的直接取出返回,對于還未登記的,先登記,然后取出返回\x0d\x0a * @param name\x0d\x0a * @return RegSingleton\x0d\x0a */\x0d\x0a public static RegSingleton getInstance(String name) {\x0d\x0a if (name == null) {\x0d\x0a name = "RegSingleton";\x0d\x0a }\x0d\x0a if (m_registry.get(name) == null) {\x0d\x0a try {\x0d\x0a m_registry.put(name, (RegSingleton) Class.forName(name).newInstance());\x0d\x0a } catch (InstantiationException e) {\x0d\x0a e.printStackTrace();\x0d\x0a } catch (IllegalAccessException e) {\x0d\x0a e.printStackTrace();\x0d\x0a } catch (ClassNotFoundException e) {\x0d\x0a e.printStackTrace();\x0d\x0a }\x0d\x0a }\x0d\x0a return m_registry.get(name);\x0d\x0a }\x0d\x0a /**\x0d\x0a * 一個(gè)示意性的商業(yè)方法\x0d\x0a * @return String\x0d\x0a */\x0d\x0a public String about() {\x0d\x0a return "Hello,I am RegSingleton!";\x0d\x0a }\x0d\x0a}