iT邦幫忙

2021 iThome 鐵人賽

DAY 26
0
自我挑戰組

JAVA的實作與應用系列 第 26

Day 26 Singleton Pattern、UML

Singleton Pattern:
單例模式是程式設計中常見的一種方法,其顧名思義,就是只有一個人,也就是必須保證只有一個實例存在,不可以有兩個以上的實例,應用在物件導向程式設計上。
以下是創建一個單例模式的實例:

Step1 因為是單例模式,所以必須做總量控制,使實例只存在一個,方法如下,將Singleton這個建構子創建為private,不讓別人使用。
https://ithelp.ithome.com.tw/upload/images/20211008/20140456SOhYxcLRXq.png

Step2 在static下new一個物件,且new在變數Instance下,也設為private,讓程式只能去參考這個new出來的物件。
https://ithelp.ithome.com.tw/upload/images/20211008/20140456P4qPTraL3a.png

Step3 在public裡面getInstance,代表任何人需要的時候,都去回傳已知的記憶體位置,也就是變數Instance。
https://ithelp.ithome.com.tw/upload/images/20211008/20140456TynUCw8Apc.png

UML:是一種用於指定、可視化、構建和記錄軟體系統以及業務建模和其他非軟體系統的工具。以下有一個最基本的UML例子:Class Diagram for Point

Point
-x : double
-y : double
+getx() : double
+gety() : double
+setx(double) : void
+sety(double) : void

Point:class name 類別名稱
-x : double、-y : double:data member
+getx() : double、+gety() : double、+setx(double) : void、+sety(double) : void:function member
在慣例上:
+代表public、-代表private


上一篇
Day 25 constructors、this、static
下一篇
Day 27 Inheritance
系列文
JAVA的實作與應用30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言