創建型模式
1. 單例模式(Singleton Pattern)
- 核心思想:確保一個類只有一個實例,并提供一個全局訪問點。
- 適用場景:需要共享資源的場景,如配置管理、日志記錄等。
public class Singleton {// 靜態變量保存單例實例private static Singleton instance;// 私有構造函數,防止外部實例化private Singleton() {}// 提供獲取實例的全局訪問點public static Singleton getInstance() {if (instance == null) { // 如果實例為空,則創建instance = new Singleton();}return instance; // 返回單例實例}
}
2. 工廠方法模式(Factory Method Pattern)
- 核心思想:定義一個創建對象的接口,但由子類決定實例化哪一個類。
- 適用場景:需要延遲到子類進行對象實例化時。
// 產品接口
interface Product {}// 具體產品類
class ConcreteProduct implements Product {}// 工廠接口
interface Creator {Product factoryMethod(); // 工廠方法,用于創建產品
}// 具體工廠類
class ConcreteCreator implements Creator {public Product factoryMethod() {return new ConcreteProduct(); // 返回具體產品實例}
}
3. 抽象工廠模式(Abstract Factory Pattern)
- 核心思想:提供一個接口,創建一系列相關或依賴對象,而無需指定具體類。
- 適用場景:需要創建一組相關或互相依賴的對象時。
// 抽象產品A
interface ProductA {}// 抽象產品B
interface ProductB {}// 具體產品A1
class ProductA1 implements ProductA {}// 具體產品B1
class ProductB1 implements ProductB {}// 抽象工廠接口
interface AbstractFactory {ProductA createProductA(); // 創建產品A的方法ProductB createProductB(); // 創建產品B的方法
}// 具體工廠1
class ConcreteFactory1 implements AbstractFactory {public ProductA createProductA() {return new ProductA1(); // 創建具體產品A1}public ProductB createProductB() {return new ProductB1(); // 創建具體產品B1}
}
4. 建造者模式(Builder Pattern)
- 核心思想:將一個復雜對象的構建與其表示分離,使得同樣的構建過程可以創建不同的表示。
- 適用場景:需要構建復雜對象時,且構建過程獨立于表示。
// 產品類
class Product {private String partA;private String partB;// 設置部件Apublic void setPartA(String partA) {this.partA = partA;}// 設置部件Bpublic void setPartB(String partB) {this.partB = partB;}
}// 建造者接口
interface Builder {void buildPartA(); // 構建部件Avoid buildPartB(); // 構建部件BProduct getResult(); // 獲取構建的產品
}// 具體建造者
class ConcreteBuilder implements Builder {private Product product = new Product();public void buildPartA() {product.setPartA("PartA"); // 設置產品的部件A}public void buildPartB() {product.setPartB("PartB"); // 設置產品的部件B}public Product getResult() {return product; // 返回構建的產品}
}
5. 原型模式(Prototype Pattern)
- 核心思想:通過復制現有實例來創建新對象,避免重復初始化。
- 適用場景:需要大量相似對象時。
// 原型類
class Prototype implements Cloneable {// 克隆方法public Prototype clone() throws CloneNotSupportedException {return (Prototype) super.clone(); // 調用父類的克隆方法}
}
結構型模式
6. 適配器模式(Adapter Pattern)
- 核心思想:將一個類的接口轉換成客戶期望的另一個接口。
- 適用場景:接口不兼容但需要協同工作的類。
// 目標接口
interface Target {void request();
}// 被適配的類
class Adaptee {void specificRequest() {// 特殊請求}
}// 適配器類
class Adapter implements Target {private Adaptee adaptee;public Adapter(Adaptee adaptee) {this.adaptee = adaptee;}public void request() {adaptee.specificRequest(); // 轉發請求到被適配對象}
}
7. 橋接模式(Bridge Pattern)
- 核心思想:將抽象部分與實現部分分離,使它們可以獨立變化。
- 適用場景:需要跨越多個平臺的對象。
// 實現接口
interface Implementor {void operationImpl();
}// 具體實現類A
class ConcreteImplementorA implements Implementor {public void operationImpl() {// 具體實現}
}// 抽象類
abstract class Abstraction {protected Implementor implementor;protected Abstraction(Implementor implementor) {this.implementor = implementor;}public abstract void operation(); // 抽象方法
}// 擴展抽象類
class RefinedAbstraction extends Abstraction {public RefinedAbstraction(Implementor implementor) {super(implementor);}public void operation() {implementor.operationImpl(); // 調用實現方法}
}
8. 組合模式(Composite Pattern)
- 核心思想:將對象組合成樹形結構以表示“部分-整體”的層次結構。
- 適用場景:需要處理樹形結構數據時。
// 組件接口
interface Component {void operation();
}// 葉子節點
class Leaf implements Component {public void operation() {// 葉子節點的操作}
}// 組合節點
class Composite implements Component {private List<Component> children = new ArrayList<>();// 添加子節點public void add(Component component) {children.add(component);}public void operation() {for (Component child : children) {child.operation(); // 遞歸調用子節點的操作}}
}
9. 裝飾器模式(Decorator Pattern)
- 核心思想:動態地給對象添加一些額外的職責。
- 適用場景:需要擴展類的功能時。
// 組件接口
interface Component {void operation();
}// 具體組件
class ConcreteComponent implements Component {public void operation() {// 基本操作}
}// 裝飾器抽象類
abstract class Decorator implements Component {protected Component component;protected Decorator(Component component) {this.component = component;}public void operation() {component.operation(); // 調用被裝飾對象的操作}
}// 具體裝飾器
class ConcreteDecorator extends Decorator {public ConcreteDecorator(Component component) {super(component);}public void operation() {super.operation();// 添加額外的操作}
}
10. 外觀模式(Facade Pattern)
- 核心思想:為子系統中的一組接口提供一個一致的界面。
- 適用場景:簡化復雜系統的使用。
// 子系統A
class SubsystemA {void operationA() {// 子系統A的操作}
}// 子系統B
class SubsystemB {void operationB() {// 子系統B的操作}
}// 外觀類
class Facade {private SubsystemA subsystemA = new SubsystemA();private SubsystemB subsystemB = new SubsystemB();// 提供的統一接口void operation() {subsystemA.operationA(); // 調用子系統A的方法subsystemB.operationB(); // 調用子系統B的方法}
}
11. 享元模式(Flyweight Pattern)
- 核心思想:運用共享技術有效地支持大量細粒度對象。
- 適用場景:需要大量創建對象時,減少內存消耗。
// 享元類
class Flyweight {private String intrinsicState; // 內部狀態public Flyweight(String intrinsicState) {this.intrinsicState = intrinsicState;}// 操作方法,傳入外部狀態void operation(String extrinsicState) {// 使用內部狀態和外部狀態}
}// 享元工廠
class FlyweightFactory {private Map<String, Flyweight> flyweights = new HashMap<>();// 獲取享元對象public Flyweight getFlyweight(String key) {if (!flyweights.containsKey(key)) {flyweights.put(key, new Flyweight(key)); // 創建新享元對象}return flyweights.get(key); // 返回享元對象}
}
12. 代理模式(Proxy Pattern)
- 核心思想:為其他對象提供一種代理,以控制對這個對象的訪問。
- 適用場景:需要控制對象訪問權限時。
// 抽象主題
interface Subject {void request();
}// 真實主題
class RealSubject implements Subject {public void request() {// 真實請求的處理}
}// 代理類
class Proxy implements Subject {private RealSubject realSubject;public void request() {if (realSubject == null) {realSubject = new RealSubject(); // 延遲初始化}realSubject.request(); // 轉發請求}
}
行為型模式
13. 責任鏈模式(Chain of Responsibility Pattern)
- 核心思想:避免請求發送者與接收者耦合,讓多個對象都有機會處理請求。
- 適用場景:請求需要多個對象處理時。
// 處理者抽象類
abstract class Handler {protected Handler successor; // 后繼者// 設置后繼者public void setSuccessor(Handler successor) {this.successor = successor;}// 處理請求public abstract void handleRequest();
}// 具體處理者1
class ConcreteHandler1 extends Handler {public void handleRequest() {if (successor != null) {successor.handleRequest(); // 轉發請求}}
}
14. 命令模式(Command Pattern)
- 核心思想:將請求封裝成對象,從而使你可用不同的請求對客戶進行參數化。
- 適用場景:需要對請求排隊、日志、撤銷操作時。
// 命令接口
interface Command {void execute();
}// 具體命令
class ConcreteCommand implements Command {private Receiver receiver; // 命令的接收者public ConcreteCommand(Receiver receiver) {this.receiver = receiver;}public void execute() {receiver.action(); // 執行接收者的動作}
}// 接收者
class Receiver {void action() {// 執行動作}
}// 調用者
class Invoker {private Command command;// 設置命令public void setCommand(Command command) {this.command = command;}// 執行命令public void executeCommand() {command.execute();}
}
15. 解釋器模式(Interpreter Pattern)
- 核心思想:為給定的語言定義文法表示,并定義一個解釋器來處理這個文法。
- 適用場景:需要解釋一種語言時。
// 表達式接口
interface Expression {int interpret();
}// 數字表達式
class Number implements Expression {private int number;public Number(int number) {this.number = number;}public int interpret() {return number; // 返回數字的值}
}// 加法表達式
class Plus implements Expression {private Expression leftOperand;private Expression rightOperand;public Plus(Expression left, Expression right) {this.leftOperand = left;this.rightOperand = right;}public int interpret() {return leftOperand.interpret() + rightOperand.interpret(); // 返回加法結果}
}
16. 迭代器模式(Iterator Pattern)
- 核心思想:提供一種方法順序訪問一個聚合對象中的各個元素,而不暴露其內部表示。
- 適用場景:需要遍歷聚合對象時。
// 迭代器接口
interface Iterator {boolean hasNext(); // 是否有下一個元素Object next(); // 獲取下一個元素
}// 聚合接口
interface Aggregate {Iterator createIterator(); // 創建迭代器
}// 具體聚合類
class ConcreteAggregate implements Aggregate {private List<Object> items = new ArrayList<>();public Iterator createIterator() {return new ConcreteIterator(this); // 創建具體迭代器}
}// 具體迭代器
class ConcreteIterator implements Iterator {private ConcreteAggregate aggregate;private int index;public ConcreteIterator(ConcreteAggregate aggregate) {this.aggregate = aggregate;}public boolean hasNext() {return index < aggregate.items.size(); // 判斷是否有下一個元素}public Object next() {return aggregate.items.get(index++); // 返回下一個元素}
}
17. 中介者模式(Mediator Pattern)
- 核心思想:用一個中介對象來封裝一系列對象的交互,使得對象之間不需要顯式地相互引用。
- 適用場景:需要減少對象之間的依賴時。
// 中介者接口
interface Mediator {void notify(Component sender, String event); // 通知方法
}// 具體中介者
class ConcreteMediator implements Mediator {private Component1 component1;private Component2 component2;// 注冊組件1public void registerComponent1(Component1 component) {this.component1 = component;}// 注冊組件2public void registerComponent2(Component2 component) {this.component2 = component;}public void notify(Component sender, String event) {if (sender == component1 && event.equals("A")) {component2.doSomething(); // 組件1觸發事件A,組件2響應} else if (sender == component2 && event.equals("B")) {component1.doSomething(); // 組件2觸發事件B,組件1響應}}
}// 組件抽象類
abstract class Component {protected Mediator mediator;public Component(Mediator mediator) {this.mediator = mediator;}
}// 組件1
class Component1 extends Component {public Component1(Mediator mediator) {super(mediator);}public void doSomething() {mediator.notify(this, "A"); // 執行操作并通知中介者}
}// 組件2
class Component2 extends Component {public Component2(Mediator mediator) {super(mediator);}public void doSomething() {mediator.notify(this, "B"); // 執行操作并通知中介者}
}
18. 備忘錄模式(Memento Pattern)
- 核心思想:在不破壞封裝性的前提下,捕獲一個對象的內部狀態,并在該對象之外保存這個狀態。
- 適用場景:需要保存和恢復對象狀態時。
// 備忘錄類
class Memento {private String state; // 狀態public Memento(String state) {this.state = state;}public String getState() {return state; // 獲取狀態}
}// 原發器類
class Originator {private String state;public void setState(String state) {this.state = state; // 設置狀態}public Memento saveStateToMemento() {return new Memento(state); // 保存狀態到備忘錄}public void getStateFromMemento(Memento memento) {state = memento.getState(); // 從備忘錄恢復狀態}
}// 管理者類
class Caretaker {private List<Memento> mementoList = new ArrayList<>();public void add(Memento state) {mementoList.add(state); // 添加備忘錄}public Memento get(int index) {return mementoList.get(index); // 獲取備忘錄}
}
19. 觀察者模式(Observer Pattern)
- 核心思想:定義對象間的一對多依賴關系,當一個對象狀態改變時,所有依賴它的對象都得到通知并被自動更新。
- 適用場景:需要觀察對象狀態變化時。
// 觀察者接口
interface Observer {void update(String state); // 更新方法
}// 具體觀察者
class ConcreteObserver implements Observer {public void update(String state) {// 處理更新}
}// 主題類
class Subject {private List<Observer> observers = new ArrayList<>(); // 觀察者列表private String state;public void attach(Observer observer) {observers.add(observer); // 添加觀察者}public void setState(String state) {this.state = state;notifyAllObservers(); // 通知所有觀察者}private void notifyAllObservers() {for (Observer observer : observers) {observer.update(state); // 更新觀察者}}
}
20. 狀態模式(State Pattern)
- 核心思想:允許對象在內部狀態改變時改變它的行為。對象看起來似乎修改了它的類。
- 適用場景:對象狀態改變時行為也改變時。
// 狀態接口
interface State {void handle(Context context); // 處理方法
}// 具體狀態A
class ConcreteStateA implements State {public void handle(Context context) {context.setState(new ConcreteStateB()); // 轉換到狀態B}
}// 具體狀態B
class ConcreteStateB implements State {public void handle(Context context) {context.setState(new ConcreteStateA()); // 轉換到狀態A}
}// 上下文類
class Context {private State state;public Context(State state) {this.state = state; // 設置初始狀態}public void setState(State state) {this.state = state; // 設置狀態}public void request() {state.handle(this); // 請求處理}
}
21. 策略模式(Strategy Pattern)
- 核心思想:定義一系列算法,把它們一個個封裝起來,并且使它們可互相替換。
- 適用場景:需要動態選擇算法時。
// 策略接口
interface Strategy {void execute(); // 執行方法
}// 具體策略A
class ConcreteStrategyA implements Strategy {public void execute() {// 策略A的實現}
}// 具體策略B
class ConcreteStrategyB implements Strategy {public void execute() {// 策略B的實現}
}// 上下文類
class Context {private Strategy strategy;public Context(Strategy strategy) {this.strategy = strategy; // 設置初始策略}public void setStrategy(Strategy strategy) {this.strategy = strategy; // 設置策略}public void executeStrategy() {strategy.execute(); // 執行策略}
}
22. 模板方法模式(Template Method Pattern)
- 核心思想:定義一個操作中的算法的骨架,而將一些步驟延遲到子類中。
- 適用場景:多個類有相似算法時。
// 抽象類
abstract class AbstractClass {// 模板方法public final void templateMethod() {primitiveOperation1();primitiveOperation2();}// 基本操作1protected abstract void primitiveOperation1();// 基本操作2protected abstract void primitiveOperation2();
}// 具體類
class ConcreteClass extends AbstractClass {protected void primitiveOperation1() {// 實現基本操作1}protected void primitiveOperation2() {// 實現基本操作2}
}
23. 訪問者模式(Visitor Pattern)
- 核心思想:將數據結構和作用于結構上的操作解耦,使得操作集合可獨立變化。
- 適用場景:需要對對象結構中的對象實施多種操作時。
// 訪問者接口
interface Visitor {void visit(ElementA element);void visit(ElementB element);
}// 元素接口
interface Element {void accept(Visitor visitor); // 接受訪問者
}// 具體元素A
class ElementA implements Element {public void accept(Visitor visitor) {visitor.visit(this); // 接受訪問者}
}// 具體元素B
class ElementB implements Element {public void accept(Visitor visitor) {visitor.visit(this); // 接受訪問者}
}// 具體訪問者
class ConcreteVisitor implements Visitor {public void visit(ElementA element) {// 訪問元素A的操作}public void visit(ElementB element) {// 訪問元素B的操作}
}
總結
設計模式為我們提供了一種標準化的解決方案,可以應對軟件開發中常見的問題。通過理解和應用這些模式,我們可以編寫出更具可維護性、可擴展性和可重用性的代碼。希望這篇博客能幫助你更好地理解和使用設計模式。每種模式都有其獨特的應用場景,選擇合適的模式可以顯著提高代碼質量和開發效率。