# 常见设计模式总结

## 创建型模式

创建型模式主要关注对象的创建过程，常见的模式包括：

### 1. 单例模式 (Singleton)

确保一个类只有一个实例，并提供全局访问点。

**应用场景**:

* 配置管理类
* 线程池管理

**示例代码**:

```java
public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
```

### 2. 工厂方法模式 (Factory Method)

定义一个用于创建对象的接口，让子类决定实例化哪一个类。

**应用场景**:

* 当一个类不知道它所必须创建的对象的类时

**示例代码**:

```java
abstract class Product {
    public abstract void use();
}

class ConcreteProductA extends Product {
    public void use() {
        System.out.println("Using Product A");
    }
}

abstract class Creator {
    public abstract Product factoryMethod();
}

class ConcreteCreatorA extends Creator {
    public Product factoryMethod() {
        return new ConcreteProductA();
    }
}
```

### 3. 抽象工厂模式 (Abstract Factory)

提供一个接口，用于创建相关或依赖对象的家族，而无需指定具体类。

**应用场景**:

* 需要创建一系列相关的产品对象

**示例代码**:

```java
interface GUIFactory {
    Button createButton();
    Checkbox createCheckbox();
}

class WinFactory implements GUIFactory {
    public Button createButton() {
        return new WinButton();
    }
    public Checkbox createCheckbox() {
        return new WinCheckbox();
    }
}
```

### 4. 建造者模式 (Builder)

将一个复杂对象的构建与表示分离，使得同样的构建过程可以创建不同的表示。

**应用场景**:

* 创建复杂对象的过程

**示例代码**:

```java
class Product {
    private String partA;
    private String partB;

    public void setPartA(String partA) { this.partA = partA; }
    public void setPartB(String partB) { this.partB = partB; }
}

class Builder {
    private Product product = new Product();

    public void buildPartA() { product.setPartA("Part A"); }
    public void buildPartB() { product.setPartB("Part B"); }
    public Product getResult() { return product; }
}
```

### 5. 原型模式 (Prototype)

通过复制现有的实例来创建新的实例。

**应用场景**:

* 当创建对象的成本较高时

**示例代码**:

```java
abstract class Prototype {
    public abstract Prototype clone();
}

class ConcretePrototype extends Prototype {
    public Prototype clone() {
        return new ConcretePrototype();
    }
}
```

## 结构型模式

结构型模式关注类或对象的组合，常见的模式包括：

### 1. 适配器模式 (Adapter)

将一个类的接口转换成客户希望的另一个接口。

**应用场景**:

* 需要使用一个已有的类，但其接口不符合需求

**示例代码**:

```java
class Adaptee {
    public void specificRequest() {
        System.out.println("Specific request");
    }
}

class Adapter extends Adaptee {
    public void request() {
        specificRequest();
    }
}
```

### 2. 装饰器模式 (Decorator)

动态地给一个对象添加一些额外的职责。

**应用场景**:

* 需要扩展一个类的功能

**示例代码**:

```java
interface Coffee {
    String getDescription();
    double cost();
}

class SimpleCoffee implements Coffee {
    public String getDescription() { return "Simple coffee"; }
    public double cost() { return 5; }
}

class MilkDecorator implements Coffee {
    private Coffee coffee;

    public MilkDecorator(Coffee coffee) { this.coffee = coffee; }
    public String getDescription() { return coffee.getDescription() + ", milk"; }
    public double cost() { return coffee.cost() + 1; }
}
```

### 3. 代理模式 (Proxy)

为其他对象提供一种代理以控制对这个对象的访问。

**应用场景**:

* 需要控制对某个对象的访问

**示例代码**:

```java
interface Subject {
    void request();
}

class RealSubject implements Subject {
    public void request() {
        System.out.println("Real subject request");
    }
}

class Proxy implements Subject {
    private RealSubject realSubject;

    public void request() {
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        realSubject.request();
    }
}
```

### 4. 外观模式 (Facade)

为复杂子系统提供一个统一的接口。

**应用场景**:

* 简化与复杂系统的交互

**示例代码**:

```java
class SubsystemA {
    public void operationA() { System.out.println("Operation A"); }
}

class SubsystemB {
    public void operationB() { System.out.println("Operation B"); }
}

class Facade {
    private SubsystemA a = new SubsystemA();
    private SubsystemB b = new SubsystemB();

    public void operation() {
        a.operationA();
        b.operationB();
    }
}
```

### 5. 桥接模式 (Bridge)

将抽象部分与实现部分分离，使它们可以独立变化。

**应用场景**:

* 当需要在多个维度上变化时

**示例代码**:

```java
interface Implementor {
    void operation();
}

class ConcreteImplementorA implements Implementor {
    public void operation() { System.out.println("Implementation A"); }
}

abstract class Abstraction {
    protected Implementor implementor;

    public Abstraction(Implementor implementor) { this.implementor = implementor; }
    public abstract void operation();
}

class RefinedAbstraction extends Abstraction {
    public RefinedAbstraction(Implementor implementor) { super(implementor); }
    public void operation() { implementor.operation(); }
}
```

### 6. 组合模式 (Composite)

将对象组合成树形结构以表示部分-整体的层次。

**应用场景**:

* 需要表示部分与整体的层次结构

**示例代码**:

```java
interface Component {
    void operation();
}

class Leaf implements Component {
    public void operation() { System.out.println("Leaf 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();
        }
    }
}
```

### 7. 享元模式 (Flyweight)

运用共享技术有效地支持大量细粒度的对象。

**应用场景**:

* 当需要大量相似对象时

**示例代码**:

```java
class Flyweight {
    private String intrinsicState;

    public Flyweight(String intrinsicState) {
        this.intrinsicState = intrinsicState;
    }

    public void operation(String extrinsicState) {
        System.out.println("Intrinsic: " + intrinsicState + ", Extrinsic: " + 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);
    }
}
```

## 行为型模式

行为型模式关注对象之间的交互，常见的模式包括：

### 1. 观察者模式 (Observer)

定义对象之间的一对多依赖关系，当一个对象改变状态时，所有依赖于它的对象都得到通知。

**应用场景**:

* 事件处理系统

**示例代码**:

```java
interface Observer {
    void update(String message);
}

class ConcreteObserver implements Observer {
    public void update(String message) {
        System.out.println("Received message: " + message);
    }
}

class Subject {
    private List<Observer> observers = new ArrayList<>();

    public void attach(Observer observer) { observers.add(observer); }

    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}
```

### 2. 策略模式 (Strategy)

定义一系列算法, 将每一个算法封装起来, 并使它们可以互换。

**应用场景**:

* 需要在运行时选择算法

**示例代码**:

```java
interface Strategy {
    void execute();
}

class ConcreteStrategyA implements Strategy {
    public void execute() { System.out.println("Strategy A"); }
}

class Context {
    private Strategy strategy;

    public Context(Strategy strategy) { this.strategy = strategy; }
    public void executeStrategy() { strategy.execute(); }
}
```

### 3. 命令模式 (Command)

将请求封装为对象，从而使您可以使用不同的请求、队列或日志请求，以及支持可撤销操作。

**应用场景**:

* 需要将操作参数化

**示例代码**:

```java
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 {
    public void action() { System.out.println("Receiver action"); }
}

class Invoker {
    private Command command;

    public void setCommand(Command command) { this.command = command; }
    public void executeCommand() { command.execute(); }
}
```

### 4. 状态模式 (State)

允许对象在内部状态改变时改变它的行为。

**应用场景**:

* 需要根据状态改变行为

**示例代码**:

```java
interface State {
    void handle();
}

class ConcreteStateA implements State {
    public void handle() { System.out.println("Handling State A"); }
}

class Context {
    private State state;

    public void setState(State state) { this.state = state; }
    public void request() { state.handle(); }
}
```

### 5. 责任链模式 (Chain of Responsibility)

使多个对象都有机会处理请求，从而避免请求发送者与接收者之间的耦合。

**应用场景**:

* 处理请求的不同级别

**示例代码**:

```java
abstract class Handler {
    protected Handler next;

    public void setNext(Handler next) { this.next = next; }
    public abstract void handleRequest(int request);
}

class ConcreteHandlerA extends Handler {
    public void handleRequest(int request) {
        if (request < 10) {
            System.out.println("Handler A handling request " + request);
        } else if (next != null) {
            next.handleRequest(request);
        }
    }
}

class ConcreteHandlerB extends Handler {
    public void handleRequest(int request) {
        if (request >= 10) {
            System.out.println("Handler B handling request " + request);
        }
    }
}
```

### 6. 备忘录模式 (Memento)

在不违反封装性的前提下，捕获一个对象的内部状态，并在该对象之外保存这个状态。

**应用场景**:

* 需要保存和恢复对象的状态

**示例代码**:

```java
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(); }
}
```

### 7. 访问者模式 (Visitor)

表示一个作用于某对象结构中的各元素的操作。

**应用场景**:

* 需要对对象结构中的元素进行操作

**示例代码**:

```java
interface Visitor {
    void visit(Element element);
}

class ConcreteVisitor implements Visitor {
    public void visit(Element element) {
        System.out.println("Visiting " + element.getName());
    }
}

abstract class Element {
    public abstract String getName();
    public abstract void accept(Visitor visitor);
}

class ConcreteElementA extends Element {
    public String getName() { return "Element A"; }
    public void accept(Visitor visitor) { visitor.visit(this); }
}
```

### 8. 中介者模式 (Mediator)

定义一个中介对象来封装一系列的对象交互。

**应用场景**:

* 需要减少多个对象之间的复杂交互

**示例代码**:

```java
class Mediator {
    private ColleagueA colleagueA;
    private ColleagueB colleagueB;

    public void setColleagueA(ColleagueA colleagueA) { this.colleagueA = colleagueA; }
    public void setColleagueB(ColleagueB colleagueB) { this.colleagueB = colleagueB; }

    public void colleagueChanged() {
        // 处理交互逻辑
    }
}

class ColleagueA {
    private Mediator mediator;

    public ColleagueA(Mediator mediator) { this.mediator = mediator; }
}

class ColleagueB {
    private Mediator mediator;

    public ColleagueB(Mediator mediator) { this.mediator = mediator; }
}
```

### 9. 解释器模式 (Interpreter)

给定一个语言, 定义它的文法表示, 并定义一个解释器来处理该语言。

**应用场景**:

* 需要解释特定语言的场景

**示例代码**:

```java
interface Expression {
    boolean interpret(String context);
}

class TerminalExpression implements Expression {
    private String data;

    public TerminalExpression(String data) { this.data = data; }
    public boolean interpret(String context) { return context.contains(data); }
}

class OrExpression implements Expression {
    private Expression expr1;
    private Expression expr2;

    public OrExpression(Expression expr1, Expression expr2) {
        this.expr1 = expr1;
        this.expr2 = expr2;
    }

    public boolean interpret(String context) {
        return expr1.interpret(context) || expr2.interpret(context);
    }
}
```
