摘要:設計模式是軟件工程中解決常見問題的經典方案。本文結合Java語言特性,深入解析常用設計模式的核心思想、實現方式及實際應用場景,幫助開發者提升代碼質量和可維護性。
一、設計模式概述
1.1 什么是設計模式?
設計模式(Design Pattern)是經過驗證的、可重復使用的代碼設計經驗總結,分為創建型、結構型和行為型三大類,共23種經典模式。
1.2 學習設計模式的意義
- 提高代碼復用性
- 增強系統擴展性
- 提升團隊協作效率
- 優化代碼結構
二、創建型模式實踐
2.1 單例模式(Singleton)
場景:全局唯一對象(如配置管理器)
public class Singleton {private static volatile Singleton instance;private Singleton() {}public static Singleton getInstance() {if (instance == null) {synchronized (Singleton.class) {if (instance == null) {instance = new Singleton();}}}return instance;}
}
特點:雙重檢查鎖實現線程安全
2.2 工廠模式(Factory)
場景:對象創建邏輯封裝
interface Shape {void draw();
}class Circle implements Shape {public void draw() {System.out.println("繪制圓形");}
}class ShapeFactory {public Shape getShape(String type) {if ("CIRCLE".equalsIgnoreCase(type)) {return new Circle();}return null;}
}
優勢:解耦客戶端與具體實現類
三、結構型模式解析
3.1 適配器模式(Adapter)
場景:接口兼容轉換
class LegacySystem {public void legacyRequest() {System.out.println("舊系統請求");}
}interface NewSystem {void request();
}class Adapter implements NewSystem {private LegacySystem legacy = new LegacySystem();public void request() {legacy.legacyRequest();}
}
3.2 裝飾器模式(Decorator)
場景:動態擴展功能
interface Coffee {double getCost();
}class BasicCoffee implements Coffee {public double getCost() { return 2.0; }
}abstract class CoffeeDecorator implements Coffee {protected Coffee decoratedCoffee;public CoffeeDecorator(Coffee coffee) {this.decoratedCoffee = coffee;}
}class MilkDecorator extends CoffeeDecorator {public MilkDecorator(Coffee coffee) {super(coffee);}public double getCost() {return super.decoratedCoffee.getCost() + 0.5;}
}
四、行為型模式應用
4.1 觀察者模式(Observer)
場景:事件驅動系統
interface Observer {void update(String message);
}class ConcreteObserver implements Observer {public void update(String message) {System.out.println("收到通知:" + message);}
}class Subject {private List<Observer> observers = new ArrayList<>();public void addObserver(Observer o) {observers.add(o);}public void notifyObservers(String message) {observers.forEach(o -> o.update(message));}
}
4.2 策略模式(Strategy)
場景:算法靈活切換
interface PaymentStrategy {void pay(double amount);
}class AlipayStrategy implements PaymentStrategy {public void pay(double amount) {System.out.println("支付寶支付:" + amount);}
}class PaymentContext {private PaymentStrategy strategy;public void setStrategy(PaymentStrategy strategy) {this.strategy = strategy;}public void executePayment(double amount) {strategy.pay(amount);}
}
五、模式選擇指南
模式類型 | 典型場景 | 常用模式 |
---|---|---|
創建型 | 對象創建管理 | 工廠、單例、建造者 |
結構型 | 類/對象組合 | 適配器、代理、裝飾器 |
行為型 | 對象交互 | 觀察者、策略、模板方法 |