Java设计模式之开篇

设计模式是软件设计的基石,能有效解决复杂代码中的重复问题。本文完整解析GoF提出的 23种设计模式,结合代码示例和实际场景,助你彻底掌握设计模式精髓!


一、创建型模式(5种)

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. 工厂方法模式(Factory Method)

核心思想:由子类决定实例化哪个类。
应用场景:数据库驱动切换、日志记录器。

interface Shape { void draw(); }
class Circle implements Shape { public void draw() { System.out.println("绘制圆形"); } }

class ShapeFactory {
    public Shape createShape(String type) {
        return switch (type) {
            case "Circle" -> new Circle();
            default -> throw new IllegalArgumentException("未知类型");
        };
    }
}

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

核心思想:创建一组相关对象家族。
应用场景:跨平台UI组件(按钮、文本框)。

interface GUIFactory {
    Button createButton();
}
class WinFactory implements GUIFactory {
    public Button createButton() { return new WinButton(); }
}
class MacFactory implements GUIFactory {
    public Button createButton() { return new MacButton(); }
}

4. 建造者模式(Builder)

核心思想:分步骤构建复杂对象。
应用场景:生成复杂文档(如HTML)、订单配置。

class Computer {
    private String cpu, ram;
    static class Builder {
        private Computer computer = new Computer();
        public Builder setCpu(String cpu) { computer.cpu = cpu; return this; }
        public Computer build() { return computer; }
    }
}
// 使用:new Computer.Builder().setCpu("Intel").build();

5. 原型模式(Prototype)

核心思想:克隆代替重复初始化。
应用场景:游戏角色复制、配置模板。

class Sheep implements Cloneable {
    public Sheep clone() throws CloneNotSupportedException {
        return (Sheep) super.clone();
    }
}

二、结构型模式(7种)

6. 适配器模式(Adapter)

核心思想:接口转换兼容。
应用场景:旧系统升级、第三方库集成。

class LegacyLibrary {
    public void legacyRequest() { System.out.println("旧接口调用"); }
}
class Adapter implements Target {
    private LegacyLibrary legacy = new LegacyLibrary();
    public void request() { legacy.legacyRequest(); }
}

7. 桥接模式(Bridge)

核心思想:抽象与实现解耦。
应用场景:形状与颜色组合(红色圆形、蓝色方形)。

interface Color { void applyColor(); }
abstract class Shape {
    protected Color color;
    public Shape(Color color) { this.color = color; }
    abstract void draw();
}
class Circle extends Shape {
    public void draw() { color.applyColor(); System.out.println("圆形"); }
}

8. 组合模式(Composite)

核心思想:树形结构处理部分-整体关系。
应用场景:文件系统目录、菜单树。

interface FileSystemComponent {
    void display();
}
class File implements FileSystemComponent {
    public void display() { System.out.println("文件"); }
}
class Directory implements FileSystemComponent {
    private List children = new ArrayList<>();
    public void add(FileSystemComponent c) { children.add(c); }
    public void display() { children.forEach(FileSystemComponent::display); }
}

9. 装饰器模式(Decorator)

核心思想:动态添加职责。
应用场景:Java IO流增强(BufferedInputStream)。

interface Coffee { double getCost(); }
class SimpleCoffee implements Coffee { public double getCost() { return 10; } }
class MilkDecorator implements Coffee {
    private Coffee coffee;
    public MilkDecorator(Coffee coffee) { this.coffee = coffee; }
    public double getCost() { return coffee.getCost() + 2; }
}

10. 外观模式(Facade)

核心思想:简化复杂系统调用。
应用场景:启动计算机(封装CPU、内存等操作)。

class ComputerFacade {
    private CPU cpu = new CPU();
    private Memory memory = new Memory();
    public void start() { cpu.start(); memory.load(); }
}

11. 享元模式(Flyweight)

核心思想:共享细粒度对象节省内存。
应用场景:文本编辑器字符对象池。

class Character {
    private char symbol; // 内部状态
    public Character(char c) { this.symbol = c; }
    public void display(int x, int y) { /* 外部状态x,y */ }
}
class CharacterFactory {
    private static Map pool = new HashMap<>();
    public static Character getCharacter(char c) {
        if (!pool.containsKey(c)) pool.put(c, new Character(c));
        return pool.get(c);
    }
}

12. 代理模式(Proxy)

核心思想:控制对象访问。
应用场景:图片懒加载、权限验证。

interface Image { void display(); }
class RealImage implements Image { public void display() { System.out.println("显示图片"); } }
class ProxyImage implements Image {
    private RealImage realImage;
    public void display() {
        if (realImage == null) realImage = new RealImage();
        realImage.display();
    }
}

三、行为型模式(11种)

13. 责任链模式(Chain of Responsibility)

核心思想:链式传递请求。
应用场景:审批流程、异常处理。

abstract class Logger {
    protected Logger next;
    public void setNext(Logger next) { this.next = next; }
    abstract void log(String message, int level);
}
class ErrorLogger extends Logger {
    public void log(String message, int level) {
        if (level <= 2) System.out.println("Error: " + message);
        else if (next != null) next.log(message, level);
    }
}

14. 命令模式(Command)

核心思想:将请求封装为对象。
应用场景:GUI按钮操作、事务管理。

interface Command { void execute(); }
class LightOnCommand implements Command {
    private Light light;
    public void execute() { light.on(); }
}
class RemoteControl {
    private Command command;
    public void setCommand(Command c) { this.command = c; }
    public void pressButton() { command.execute(); }
}

15. 解释器模式(Interpreter)

核心思想:定义语法规则并解释。
应用场景:SQL解析、数学表达式计算。

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); }
}

16. 迭代器模式(Iterator)

核心思想:统一遍历集合元素。
应用场景:Java集合框架中的Iterator

class BookList implements Iterable {
    private String[] books = {"Java", "Python"};
    public Iterator iterator() {
        return new Iterator<>() {
            private int index = 0;
            public boolean hasNext() { return index < books.length; }
            public String next() { return books[index++]; }
        };
    }
}

17. 中介者模式(Mediator)

核心思想:通过中介协调对象交互。
应用场景:聊天室消息转发。

class ChatRoom {
    public static void showMessage(User user, String msg) {
        System.out.println(user.getName() + ": " + msg);
    }
}
class User {
    private String name;
    public User(String name) { this.name = name; }
    public void sendMessage(String msg) { ChatRoom.showMessage(this, msg); }
}

18. 备忘录模式(Memento)

核心思想:保存和恢复对象状态。
应用场景:游戏存档、撤销操作。

class Editor {
    private String content;
    public EditorMemento save() { return new EditorMemento(content); }
    public void restore(EditorMemento m) { content = m.getContent(); }
}
class EditorMemento { private String content; /* getter和构造器省略 */ }

19. 观察者模式(Observer)

核心思想:一对多依赖通知。
应用场景:事件监听、消息发布-订阅。

class NewsAgency {
    private List observers = new ArrayList<>();
    public void addObserver(Observer o) { observers.add(o); }
    public void notifyObservers(String news) {
        for (Observer o : observers) o.update(news);
    }
}
interface Observer { void update(String news); }

20. 状态模式(State)

核心思想:状态改变导致行为变化。
应用场景:订单状态流转、电梯控制。

interface State { void handle(Context context); }
class StartState implements State {
    public void handle(Context context) { context.setState(this); }
}
class Context {
    private State state;
    public void setState(State state) { this.state = state; }
}

21. 策略模式(Strategy)

核心思想:算法族可互换。
应用场景:支付方式选择、排序策略切换。

interface PaymentStrategy { void pay(int amount); }
class CreditCardPayment implements PaymentStrategy {
    public void pay(int amount) { System.out.println("信用卡支付:" + amount); }
}
class PayPalPayment implements PaymentStrategy {
    public void pay(int amount) { System.out.println("PayPal支付:" + amount); }
}

22. 模板方法模式(Template Method)

核心思想:定义算法骨架,子类实现步骤。
应用场景:数据库操作模板、游戏初始化流程。

abstract class Game {
    abstract void initialize();
    abstract void start();
    public final void play() { initialize(); start(); }
}
class Chess extends Game {
    void initialize() { System.out.println("初始化棋盘"); }
    void start() { System.out.println("开始对弈"); }
}

23. 访问者模式(Visitor)

核心思想:数据结构与操作分离。
应用场景:编译器语法树分析、文档导出。

interface ComputerPartVisitor { void visit(Keyboard keyboard); }
class ComputerPartDisplayVisitor implements ComputerPartVisitor {
    public void visit(Keyboard keyboard) { System.out.println("显示键盘"); }
}
interface ComputerPart { void accept(Visitor visitor); }
class Keyboard implements ComputerPart {
    public void accept(Visitor visitor) { visitor.visit(this); }
}

四、总结与最佳实践

  1. 模式选择原则

    • 优先满足需求,再考虑扩展性。

    • 避免“为了用模式而用模式”,简单设计优于复杂模式。

  2. 高频模式推荐

    • 单例:全局唯一资源管理。

    • 工厂方法/抽象工厂:解耦对象创建。

    • 观察者:事件驱动系统。

    • 策略:灵活替换算法。

  3. 学习路径建议

    • 结合开源框架(如Spring)源码学习模式应用。

    • 通过重构现有代码练习模式引入。


参考资料:《Head First设计模式》《设计模式:可复用面向对象软件的基础》


如果对某个模式仍有疑问,欢迎在评论区留言讨论! 后续将推出更多设计模式详细实战案例,点击关注不迷路!

你可能感兴趣的:(java设计模式,java,设计模式,开发语言)