Design Pattern_Skill_1_What is pattern?_單例模式(Singleton Pattern)一胎化政策

What is pattern?

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design.

A design pattern isn't a finished design that can be transformed directly into code.

It is a description or template for how to solve a problem that can be used in many different situations.

模式一詞主要包含
*一個特定環節、情況
*一個問題
一個解決方案

透過總結三個元素來達成可重複使用的設計方案



設計模式(Design Pattern):主要探討針對一些特定工程環節不斷出現的問題,加以描述該問題解決方案的核心思路。藉此來無數次使用已有的解決套路更可省去重複相同工作
描述軟體物件相互溝通的既定架構用以解決特定環節中的問題。
主要是針對一個特定環節(境)問題的一套和程式語言無關的
(C#,JAVA,VB.NET,C++...etc皆可實踐)解決思路方案



單例(子)模式(Singleton Pattern):
確保一個Class只會有一個唯一實體,並且提供一個全域訪問方法。
==>有點類似像獨生子女的一胎化政策


應用環節:
(1)一個系統跳窗不允許可以重複跳多個。(常見!!!!)
你有一個表單視窗一次只能填寫送出一個但是有人可以同時開啟多個時....
這時同樣是小明送表單卻有好多個小明.....




(2)一個樓層存在多台列印機,要來設計一個打印機管理程式。
我們會設計一個負責管理列印機的class用來處理列印相關任務協調
包含從列印佇列中提取文檔
此時每次都new 一個實體
會導致同一時間多個物件都在調用列印佇列提取的衝突

解決方案:
Step1.首先將建構子用private修飾,屏蔽透過直接實體化來訪問該類構造與創立新實體。
Step2.使用static關鍵字來宣告一個靜態屬性(確保共用且唯一)
Step3.提供一個可獲得該實體的method,來回傳該class實體(每次呼叫都是調用同一實體)





程式碼:
版本1.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Singleton {
 private static Singleton singleton;
 
 private Singleton() {
  
 }
 
 public static Singleton getInstance() {
  if(null==singleton) {
   singleton = new Singleton();
  }
  return singleton;
 }
}


版本2.(更精簡版)
此版較第一版安全(當是在多thread時候,第一版有機會有漏洞)
因為當多thread去訪問時有機會會有偶發的race condition 問題產生

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class Singleton {
 private static Singleton singleton = new Singleton();
 
 private Singleton() {
  
 }
 
 public static Singleton getInstance() {
  return singleton;
 }
}


我們這裡舉一個實際工作實務中遇到的潛在性Bug修正

如何只允許開啟一個JFrame 跳窗 (使用NetBeans  IDE)




Reference link:
https://sourcemaking.com/design_patterns
https://skyyen999.gitbooks.io/-study-design-pattern-in-java/content/singleton.html
https://www.youtube.com/watch?v=0JG8S4uRlZw
https://www.youtube.com/watch?v=PGQPNKWk4oE


static vs singleton
https://www.youtube.com/watch?v=ilOkObwSWv8

Singleton design pattern in Java - Part 1&2
https://www.youtube.com/watch?v=QsBQnFUx388
https://www.youtube.com/watch?v=GH5_lhFShfU


Thread-safe singleton implementation in Java
https://www.youtube.com/watch?v=zUYLY8kYavs

Singleton Pattern Multithreading problem
https://www.youtube.com/watch?v=9dwvfo3f60w

Thread Safe Singleton Class In Java With Double Check.
https://www.youtube.com/watch?v=vlTAlbhUYps





留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題