設(shè)計(jì)模式簡(jiǎn)介
設(shè)計(jì)模式總共有23種。其目的是在代碼封裝性、可讀性、重用性、可擴(kuò)展性、可靠性等方面,使項(xiàng)目更易于開(kāi)發(fā)、維護(hù)及擴(kuò)展??梢苑譃槿箢悾瑒?chuàng)建型模式、結(jié)構(gòu)型模式、行為型模式。
- 創(chuàng)建型模式:創(chuàng)建對(duì)象的同時(shí)隱藏創(chuàng)建邏輯的方式
- 工廠模式
- 單例模式
2.結(jié)構(gòu)型模式:關(guān)注類和對(duì)象的組合,簡(jiǎn)化系統(tǒng)設(shè)計(jì)
- 外觀模式
- 代理模式
3.行為型模式:關(guān)注對(duì)象之間的通信,增加靈活性
- 策略模式
- 迭代器模式
- 觀察者模式
- 中介者模式
- 訪問(wèn)者模式
實(shí)際場(chǎng)景應(yīng)用
- 工廠模式
// 定義普通按鈕組件
class Button {
constructor(props) {
this.props = props;
}
render() {
const button = document.createElement('button');
button.innerText = this.props.text;
button.classList.add('btn');
return button;
}
}
// 定義主要按鈕組件
class PrimaryButton extends Button {
render() {
const button = super.render();
button.classList.add('btn-primary');
return button;
}
}
// 定義警告按鈕組件
class WarningButton extends Button {
render() {
const button = super.render();
button.classList.add('btn-warning');
return button;
}
}
// 按鈕工廠函數(shù),根據(jù)類型創(chuàng)建相應(yīng)的按鈕實(shí)例
function ButtonFactory(type, props) {
switch (type) {
case 'primary':
return new PrimaryButton(props);
case 'warning':
return new WarningButton(props);
default:
return new Button(props);
}
}
// 使用工廠模式創(chuàng)建按鈕實(shí)例
const button1 = ButtonFactory('primary', { text: 'Primary Button' });
const button2 = ButtonFactory('warning', { text: 'Warning Button' });
const button3 = ButtonFactory('normal', { text: 'Normal Button' });
// 在頁(yè)面上插入按鈕
document.body.appendChild(button1.render());
document.body.appendChild(button2.render());
document.body.appendChild(button3.render());
// 通過(guò)工廠模式我們可以將創(chuàng)建對(duì)象的邏輯封裝起來(lái),使得調(diào)用方只需要關(guān)心需要哪種類型的按鈕,而不需要了解每個(gè)按鈕類型的具體實(shí)現(xiàn)細(xì)節(jié)。
- 單例模式
// 登錄管理器
class LoginManager {
constructor() {
if (LoginManager.instance) {
return LoginManager.instance;
}
this.isLoggedIn = false;
LoginManager.instance = this;
}
login(username, password) {
// 登錄的邏輯
this.isLoggedIn = true;
}
logout() {
// 登出的邏輯
this.isLoggedIn = false;
}
}
const loginManager = new LoginManager();
// 無(wú)論在項(xiàng)目的何處獲取 LoginManager 的實(shí)例,都始終是同一個(gè),確保了登錄狀態(tài)的唯一性和一致性。
- 代理模式
在實(shí)現(xiàn)懶加載(Lazy Loading)、預(yù)加載(Preloading)等功能時(shí),可以使用代理模式。代理對(duì)象可以控制對(duì)原始對(duì)象的訪問(wèn),并在需要時(shí)加載或處理數(shù)據(jù)。
// 代理加載圖片類,若緩存中有,則直接返回緩存數(shù)據(jù);若沒(méi)有,則調(diào)用加載圖片類
class Image {
constructor(url) {
this.url = url
this.loadImage()
}
loadImage() {
console.log(`加載圖片 ${this.url}`)
}
}
class ProxyImage {
constructor(url) {
this.url = url
}
loadImage() {
if (!this.image) {
this.image = new Image(this.url)
}
console.log(`緩存中圖片 ${this.url}`)
}
}
const image1 = new Image('image1.jpg')
const proxyImage1 = new ProxyImage('image1.jpg')
proxyImage1.loadImage(); // 加載圖片
proxyImage1.loadImage(); // 緩存中圖片
- 外觀模式
//應(yīng)用外觀模式封裝一個(gè)統(tǒng)一的 DOM 元素事件綁定/取消方法,用于兼容不同版本的瀏覽器和更方便的調(diào)用
// 綁定事件
function addEvent(element, event, handler) {
if (element.addEventListener) {
element.addEventListener(event, handler, false)
} else if (element.attachEvent) {
element.attachEvent("on" + event, handler)
} else {
element["on" + event] = fn
}
}
// 取消綁定
function removeEvent(element, event, handler) {
if (element.removeEventListener) {
element.removeEventListener(event, handler, false)
} else if (element.detachEvent) {
element.detachEvent("on" + event, handler)
} else {
element["on" + event] = null
}
}
- 策略模式
// 定義不同的支付策略
class PaymentStrategy {
constructor() {
this.paymentMethod = null;
}
setPaymentMethod(paymentMethod) {
this.paymentMethod = paymentMethod;
}
calculatePayment(orderTotal) {
return this.paymentMethod.calculate(orderTotal);
}
}
// 定義支付方式:信用卡支付
class CreditCardPayment {
calculate(orderTotal) {
// 假設(shè)信用卡支付有 2% 的手續(xù)費(fèi)
const fee = orderTotal * 0.02;
return orderTotal + fee;
}
}
// 定義支付方式:PayPal 支付
class PayPalPayment {
calculate(orderTotal) {
// PayPal 支付沒(méi)有額外費(fèi)用
return orderTotal;
}
}
// 使用策略模式處理訂單支付
const orderTotal = 100; // 訂單總額為 100 美元
const paymentStrategy = new PaymentStrategy();
// 選擇信用卡支付方式
paymentStrategy.setPaymentMethod(new CreditCardPayment());
const totalWithCreditCard = paymentStrategy.calculatePayment(orderTotal);
console.log('Total with Credit Card:', totalWithCreditCard);
// 選擇 PayPal 支付方式
paymentStrategy.setPaymentMethod(new PayPalPayment());
const totalWithPayPal = paymentStrategy.calculatePayment(orderTotal);
console.log('Total with PayPal:', totalWithPayPal);
// PaymentStrategy 類是策略模式的上下文,它包含一個(gè)當(dāng)前支付方法的引用,并提供了一個(gè)方法 calculatePayment 來(lái)執(zhí)行具體的支付計(jì)算。
// CreditCardPayment 和 PayPalPayment 類是具體的支付策略,分別實(shí)現(xiàn)了 calculate 方法來(lái)計(jì)算訂單總額。
// 在使用過(guò)程中,我們首先創(chuàng)建了一個(gè) PaymentStrategy 實(shí)例,然后根據(jù)用戶的選擇設(shè)置不同的支付方式,并調(diào)用 calculatePayment 方法來(lái)獲取最終支付金額。
//策略模式的優(yōu)勢(shì)在于它使得算法的選擇和使用算法的客戶端分離開(kāi)來(lái),客戶端只需知道如何使用策略模式的上下文(PaymentStrategy),而不需要了解具體的算法實(shí)現(xiàn)細(xì)節(jié)。