一、Dart 單例模式
單例模式是一種常見的軟件設計模式,它旨在確保只創建一個類的實例,並為其他對象提供全局訪問點。在 dart 中實現單例模式非常簡單,只需要使用靜態變量和工廠構造函數即可。
// Singleton class
class Singleton {
static Singleton _instance;
factory Singleton() {
if (_instance == null) {
_instance = Singleton._internal();
}
return _instance;
}
Singleton._internal();
}
void main() {
Singleton s1 = Singleton();
Singleton s2 = Singleton();
print(s1 == s2); // true
}
在上面的代碼中,我們創建了一個 Singleton 類,使用靜態變量 _instance 存儲 Singleton 實例。我們還定義了一個工廠構造函數,該函數在首次調用時會創建一個 Singleton 實例,如果實例已經存在,則返回現有的實例。
二、用 Dart 寫單鏈表倒置
下面我們使用單例模式來實現單鏈表倒置,我們將使用遞歸算法,從鏈表的頭節點開始遍歷,一直到尾節點。我們還將定義一個 Singleton 類來存儲鏈表的頭節點。
class Node {
int value;
Node next;
Node(this.value, [this.next]);
}
class LinkedList {
static LinkedList _instance;
Node head;
factory LinkedList() {
if (_instance == null) {
_instance = LinkedList._internal();
}
return _instance;
}
LinkedList._internal();
Node reverseList(Node current, Node prev) {
if (current == null) {
head = prev;
return head;
}
var next = current.next;
current.next = prev;
return reverseList(next, current);
}
void add(int value) {
if (head == null) {
head = Node(value);
} else {
var current = head;
while (current.next != null) {
current = current.next;
}
current.next = Node(value);
}
}
void printList() {
var current = head;
while (current != null) {
print(current.value);
current = current.next;
}
}
}
void main() {
var list = LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
print('Original List:');
list.printList();
var head = list.head;
list.reverseList(head, null);
print('Reversed List:');
list.printList();
}
在上面的代碼中,我們使用了一個 Node 類來表示鏈表中的一個節點。我們還定義了一個 LinkedList 類,使用 _instance 靜態變量存儲實例。我們還定義了一個 add() 方法來向鏈表中添加元素,並定義了一個 printList() 方法來打印鏈表中的所有節點。我們最後定義了一個 reverseList() 方法來倒置整個鏈表。
三、Dart 單例的應用場景
單例模式在實際開發中非常有用,下面是一些常見的應用場景:
- 配置文件管理器。
- 數據庫連接池。
- 應用程序的全局狀態管理器。
- 網站的訪問統計器。
總結來說,單例模式可以幫助我們確保只有一個實例被創建,避免了一些不必要的開銷和錯誤。在 dart 中實現單例模式非常簡單,只需要使用靜態變量和工廠構造函數即可。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/152574.html