🎯 设计模式完全指南:从生活智慧到代码艺术

🎯 设计模式完全指南:从生活智慧到代码艺术

引言

设计模式是软件开发中常见问题的解决方案,它们不仅仅是代码层面的最佳实践,更是人类智慧的结晶。在我们的日常生活中,这些模式无处不在。让我们一起来探索设计模式与生活的奇妙联系。

什么是设计模式?

设计模式是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。它们分为三大类:创建型模式、结构型模式和行为型模式。

生活中的设计模式

创建型模式

1. 单例模式
  • 特点:确保一个类只有一个实例
  • 生活例子:太阳、地球、身份证
  • 应用场景:全局唯一资源管理
  • 代码示例:
java 复制代码
public class Sun {
    private static Sun instance;
    private Sun() {}
    
    public static synchronized Sun getInstance() {
        if (instance == null) {
            instance = new Sun();
        }
        return instance;
    }
}

// 使用示例
Sun sun1 = Sun.getInstance();
Sun sun2 = Sun.getInstance();
System.out.println(sun1 == sun2); // 输出: true,证明是同一个实例
2. 工厂方法模式
  • 特点:定义一个创建对象的接口,让子类决定实例化哪个类
  • 生活例子:餐厅点餐、汽车制造
  • 应用场景:需要根据条件创建不同对象
  • 代码示例:
java 复制代码
interface Food {
    void prepare();
}

class Pizza implements Food {
    public void prepare() {
        System.out.println("准备披萨");
    }
}

class Burger implements Food {
    public void prepare() {
        System.out.println("准备汉堡");
    }
}

interface FoodFactory {
    Food createFood();
}

class PizzaFactory implements FoodFactory {
    public Food createFood() {
        return new Pizza();
    }
}

class BurgerFactory implements FoodFactory {
    public Food createFood() {
        return new Burger();
    }
}

// 使用示例
FoodFactory pizzaFactory = new PizzaFactory();
Food pizza = pizzaFactory.createFood();
pizza.prepare(); // 输出: 准备披萨

FoodFactory burgerFactory = new BurgerFactory();
Food burger = burgerFactory.createFood();
burger.prepare(); // 输出: 准备汉堡
3. 抽象工厂模式
  • 特点:提供一个创建一系列相关或相互依赖对象的接口
  • 生活例子:家具套装、电子产品系列
  • 应用场景:需要创建一系列相关产品
  • 代码示例:
java 复制代码
interface FurnitureFactory {
    Chair createChair();
    Table createTable();
}

class ModernFurnitureFactory implements FurnitureFactory {
    public Chair createChair() {
        return new ModernChair();
    }
    public Table createTable() {
        return new ModernTable();
    }
}

class ClassicFurnitureFactory implements FurnitureFactory {
    public Chair createChair() {
        return new ClassicChair();
    }
    public Table createTable() {
        return new ClassicTable();
    }
}

// 使用示例
FurnitureFactory modernFactory = new ModernFurnitureFactory();
Chair modernChair = modernFactory.createChair();
Table modernTable = modernFactory.createTable();

FurnitureFactory classicFactory = new ClassicFurnitureFactory();
Chair classicChair = classicFactory.createChair();
Table classicTable = classicFactory.createTable();
4. 建造者模式
  • 特点:将一个复杂对象的构建与它的表示分离
  • 生活例子:房屋建造、汽车组装
  • 应用场景:复杂对象的创建过程
  • 代码示例:
java 复制代码
class Computer {
    private String cpu;
    private String ram;
    private String storage;
    
    public static class Builder {
        private Computer computer = new Computer();
        
        public Builder setCpu(String cpu) {
            computer.cpu = cpu;
            return this;
        }
        
        public Builder setRam(String ram) {
            computer.ram = ram;
            return this;
        }
        
        public Builder setStorage(String storage) {
            computer.storage = storage;
            return this;
        }
        
        public Computer build() {
            return computer;
        }
    }
}

// 使用示例
Computer computer = new Computer.Builder()
    .setCpu("Intel i7")
    .setRam("16GB")
    .setStorage("512GB SSD")
    .build();
5. 原型模式
  • 特点:通过克隆现有对象来创建新对象
  • 生活例子:复印机、克隆羊
  • 应用场景:需要复制现有对象
  • 代码示例:
java 复制代码
class Document implements Cloneable {
    private String content;
    
    public Document(String content) {
        this.content = content;
    }
    
    public Document clone() throws CloneNotSupportedException {
        return (Document) super.clone();
    }
}

// 使用示例
Document original = new Document("原始文档");
try {
    Document copy = original.clone();
    System.out.println("复制成功: " + copy);
} catch (CloneNotSupportedException e) {
    e.printStackTrace();
}

结构型模式

1. 适配器模式
  • 特点:将一个类的接口转换成客户希望的另一个接口
  • 生活例子:电源适配器、翻译官
  • 应用场景:接口不兼容时的转换
  • 代码示例:
java 复制代码
interface OldInterface {
    void oldMethod();
}

interface NewInterface {
    void newMethod();
}

class Adapter implements NewInterface {
    private OldInterface oldInterface;
    
    public Adapter(OldInterface oldInterface) {
        this.oldInterface = oldInterface;
    }
    
    public void newMethod() {
        oldInterface.oldMethod();
    }
}

// 使用示例
OldInterface oldInterface = new OldInterface() {
    public void oldMethod() {
        System.out.println("旧接口方法");
    }
};

NewInterface adapter = new Adapter(oldInterface);
adapter.newMethod(); // 输出: 旧接口方法
2. 桥接模式
  • 特点:将抽象部分与实现部分分离
  • 生活例子:遥控器与电视、画笔与颜料
  • 应用场景:需要多维度变化
  • 代码示例:
java 复制代码
interface DrawingAPI {
    void drawCircle(double x, double y, double radius);
}

class DrawingAPI1 implements DrawingAPI {
    public void drawCircle(double x, double y, double radius) {
        System.out.println("API1画圆");
    }
}

abstract class Shape {
    protected DrawingAPI drawingAPI;
    
    protected Shape(DrawingAPI drawingAPI) {
        this.drawingAPI = drawingAPI;
    }
    
    public abstract void draw();
}

// 使用示例
DrawingAPI api1 = new DrawingAPI1();
Shape circle = new Circle(api1, 1, 2, 3);
circle.draw(); // 输出: API1画圆
3. 组合模式
  • 特点:将对象组合成树形结构
  • 生活例子:公司组织架构、文件系统
  • 应用场景:需要表示部分-整体层次结构
  • 代码示例:
java 复制代码
interface FileSystemComponent {
    void display();
}

class File implements FileSystemComponent {
    private String name;
    
    public File(String name) {
        this.name = name;
    }
    
    public void display() {
        System.out.println("文件: " + name);
    }
}

class Directory implements FileSystemComponent {
    private List<FileSystemComponent> children = new ArrayList<>();
    private String name;
    
    public Directory(String name) {
        this.name = name;
    }
    
    public void add(FileSystemComponent component) {
        children.add(component);
    }
    
    public void display() {
        System.out.println("目录: " + name);
        for (FileSystemComponent child : children) {
            child.display();
        }
    }
}

// 使用示例
Directory root = new Directory("根目录");
File file1 = new File("文件1.txt");
File file2 = new File("文件2.txt");
Directory subDir = new Directory("子目录");
File file3 = new File("文件3.txt");

root.add(file1);
root.add(file2);
root.add(subDir);
subDir.add(file3);

root.display(); // 显示整个文件系统结构
4. 装饰器模式
  • 特点:动态地给对象添加新的职责
  • 生活例子:蛋糕装饰、手机壳
  • 应用场景:需要动态扩展功能
  • 代码示例:
java 复制代码
interface Coffee {
    double getCost();
    String getDescription();
}

class SimpleCoffee implements Coffee {
    public double getCost() {
        return 1.0;
    }
    
    public String getDescription() {
        return "简单咖啡";
    }
}

class MilkDecorator implements Coffee {
    private Coffee coffee;
    
    public MilkDecorator(Coffee coffee) {
        this.coffee = coffee;
    }
    
    public double getCost() {
        return coffee.getCost() + 0.5;
    }
    
    public String getDescription() {
        return coffee.getDescription() + " + 牛奶";
    }
}

// 使用示例
Coffee simpleCoffee = new SimpleCoffee();
System.out.println(simpleCoffee.getDescription() + " 价格: " + simpleCoffee.getCost());

Coffee milkCoffee = new MilkDecorator(simpleCoffee);
System.out.println(milkCoffee.getDescription() + " 价格: " + milkCoffee.getCost());
5. 外观模式
  • 特点:为子系统提供一个统一的接口
  • 生活例子:前台接待、统一客服
  • 应用场景:简化复杂系统的访问
  • 代码示例:
java 复制代码
class CPU {
    public void process() {
        System.out.println("CPU处理数据");
    }
}

class Memory {
    public void load() {
        System.out.println("内存加载数据");
    }
}

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

// 使用示例
ComputerFacade computer = new ComputerFacade();
computer.start(); // 输出: 内存加载数据 CPU处理数据
6. 享元模式
  • 特点:运用共享技术有效地支持大量细粒度的对象
  • 生活例子:图书馆、共享单车
  • 应用场景:需要大量相似对象
  • 代码示例:
java 复制代码
class Character {
    private char symbol;
    private String font;
    
    public Character(char symbol, String font) {
        this.symbol = symbol;
        this.font = font;
    }
    
    public void display() {
        System.out.println("显示字符: " + symbol + " 使用字体: " + font);
    }
}

class CharacterFactory {
    private Map<Character, Character> characters = new HashMap<>();
    
    public Character getCharacter(char key) {
        if (!characters.containsKey(key)) {
            characters.put(key, new Character(key, "Arial"));
        }
        return characters.get(key);
    }
}

// 使用示例
CharacterFactory factory = new CharacterFactory();
Character a1 = factory.getCharacter('a');
Character a2 = factory.getCharacter('a');
System.out.println(a1 == a2); // 输出: true,证明是同一个对象
7. 代理模式
  • 特点:为其他对象提供一种代理以控制对这个对象的访问
  • 生活例子:房产中介、律师
  • 应用场景:需要控制对象访问
  • 代码示例:
java 复制代码
interface Image {
    void display();
}

class RealImage implements Image {
    private String filename;
    
    public RealImage(String filename) {
        this.filename = filename;
        loadFromDisk();
    }
    
    private void loadFromDisk() {
        System.out.println("加载图片: " + filename);
    }
    
    public void display() {
        System.out.println("显示图片: " + filename);
    }
}

class ProxyImage implements Image {
    private RealImage realImage;
    private String filename;
    
    public ProxyImage(String filename) {
        this.filename = filename;
    }
    
    public void display() {
        if (realImage == null) {
            realImage = new RealImage(filename);
        }
        realImage.display();
    }
}

// 使用示例
Image image = new ProxyImage("test.jpg");
// 图片还没有加载
image.display(); // 第一次调用会加载图片
image.display(); // 第二次调用直接显示

行为型模式

1. 责任链模式
  • 特点:使多个对象都有机会处理请求
  • 生活例子:审批流程、客服转接
  • 应用场景:需要多个对象处理请求
  • 代码示例:
java 复制代码
abstract class Handler {
    protected Handler successor;
    
    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }
    
    public abstract void handleRequest(Request request);
}

class ConcreteHandler extends Handler {
    public void handleRequest(Request request) {
        if (canHandle(request)) {
            // 处理请求
        } else if (successor != null) {
            successor.handleRequest(request);
        }
    }
    
    private boolean canHandle(Request request) {
        // 判断是否能处理请求
        return true;
    }
}

// 使用示例
Handler handler1 = new ConcreteHandler();
Handler handler2 = new ConcreteHandler();
Handler handler3 = new ConcreteHandler();

handler1.setSuccessor(handler2);
handler2.setSuccessor(handler3);

Request request = new Request();
handler1.handleRequest(request);
2. 命令模式
  • 特点:将请求封装成对象
  • 生活例子:餐厅点餐、遥控器
  • 应用场景:需要将请求参数化
  • 代码示例:
java 复制代码
interface Command {
    void execute();
}

class LightOnCommand implements Command {
    private Light light;
    
    public LightOnCommand(Light light) {
        this.light = light;
    }
    
    public void execute() {
        light.turnOn();
    }
}

class RemoteControl {
    private Command command;
    
    public void setCommand(Command command) {
        this.command = command;
    }
    
    public void pressButton() {
        command.execute();
    }
}

// 使用示例
Light light = new Light();
Command lightOn = new LightOnCommand(light);
RemoteControl remote = new RemoteControl();

remote.setCommand(lightOn);
remote.pressButton(); // 输出: 开灯
3. 解释器模式
  • 特点:定义语言的文法,并解释该语言中的句子
  • 生活例子:翻译、编译器
  • 应用场景:需要解释特定语言
  • 代码示例:
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);
    }
}

// 使用示例
Expression terminal1 = new TerminalExpression("Hello");
Expression terminal2 = new TerminalExpression("World");
Expression orExpression = new OrExpression(terminal1, terminal2);

System.out.println(orExpression.interpret("Hello")); // 输出: true
System.out.println(orExpression.interpret("World")); // 输出: true
System.out.println(orExpression.interpret("Hi")); // 输出: false
4. 迭代器模式
  • 特点:提供一种方法顺序访问一个聚合对象中的各个元素
  • 生活例子:图书目录、播放列表
  • 应用场景:需要遍历集合对象
  • 代码示例:
java 复制代码
interface Iterator {
    boolean hasNext();
    Object next();
}

class ConcreteIterator implements Iterator {
    private List<Object> items;
    private int position = 0;
    
    public ConcreteIterator(List<Object> items) {
        this.items = items;
    }
    
    public boolean hasNext() {
        return position < items.size();
    }
    
    public Object next() {
        return items.get(position++);
    }
}

// 使用示例
List<Object> items = Arrays.asList("A", "B", "C");
Iterator iterator = new ConcreteIterator(items);

while (iterator.hasNext()) {
    System.out.println(iterator.next());
}
5. 中介者模式
  • 特点:用一个中介对象来封装一系列的对象交互
  • 生活例子:机场塔台、婚介所
  • 应用场景:对象间复杂通信
  • 代码示例:
java 复制代码
class Mediator {
    private List<Colleague> colleagues = new ArrayList<>();
    
    public void addColleague(Colleague colleague) {
        colleagues.add(colleague);
    }
    
    public void send(String message, Colleague sender) {
        for (Colleague colleague : colleagues) {
            if (colleague != sender) {
                colleague.receive(message);
            }
        }
    }
}

class Colleague {
    private Mediator mediator;
    
    public Colleague(Mediator mediator) {
        this.mediator = mediator;
    }
    
    public void send(String message) {
        mediator.send(message, this);
    }
    
    public void receive(String message) {
        System.out.println("收到消息: " + message);
    }
}

// 使用示例
Mediator mediator = new Mediator();
Colleague colleague1 = new Colleague(mediator);
Colleague colleague2 = new Colleague(mediator);

mediator.addColleague(colleague1);
mediator.addColleague(colleague2);

colleague1.send("Hello from colleague1");
6. 备忘录模式
  • 特点:在不破坏封装性的前提下,捕获一个对象的内部状态
  • 生活例子:游戏存档、撤销功能
  • 应用场景:需要保存对象状态
  • 代码示例:
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 save() {
        return new Memento(state);
    }
    
    public void restore(Memento memento) {
        state = memento.getState();
    }
}

// 使用示例
Originator originator = new Originator();
originator.setState("状态1");
Memento memento = originator.save();

originator.setState("状态2");
System.out.println("当前状态: " + originator.getState());

originator.restore(memento);
System.out.println("恢复后状态: " + originator.getState());
7. 观察者模式
  • 特点:定义对象间的一种一对多依赖关系
  • 生活例子:报纸订阅、天气预报
  • 应用场景:需要通知多个对象
  • 代码示例:
java 复制代码
interface Observer {
    void update(String 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);
        }
    }
}

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

// 使用示例
Subject subject = new Subject();
Observer observer1 = new ConcreteObserver();
Observer observer2 = new ConcreteObserver();

subject.attach(observer1);
subject.attach(observer2);

subject.notifyObservers("状态更新");
8. 状态模式
  • 特点:允许对象在内部状态改变时改变它的行为
  • 生活例子:交通信号灯、自动售货机
  • 应用场景:对象状态影响行为
  • 代码示例:
java 复制代码
interface State {
    void handle();
}

class Context {
    private State state;
    
    public void setState(State state) {
        this.state = state;
    }
    
    public void request() {
        state.handle();
    }
}

class ConcreteState implements State {
    public void handle() {
        System.out.println("处理当前状态");
    }
}

// 使用示例
Context context = new Context();
context.setState(new ConcreteState());
context.request(); // 输出: 处理当前状态
9. 策略模式
  • 特点:定义一系列算法,将每个算法封装起来
  • 生活例子:支付方式、出行方式
  • 应用场景:需要动态切换算法
  • 代码示例:
java 复制代码
interface Strategy {
    int doOperation(int num1, int num2);
}

class AddStrategy implements Strategy {
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}

class Context {
    private Strategy strategy;
    
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }
    
    public int executeStrategy(int num1, int num2) {
        return strategy.doOperation(num1, num2);
    }
}

// 使用示例
Context context = new Context(new AddStrategy());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
10. 模板方法模式
  • 特点:定义一个操作中的算法骨架
  • 生活例子:烹饪食谱、工作流程
  • 应用场景:需要固定算法步骤
  • 代码示例:
java 复制代码
abstract class Game {
    abstract void initialize();
    abstract void startPlay();
    abstract void endPlay();
    
    public final void play() {
        initialize();
        startPlay();
        endPlay();
    }
}

class Cricket extends Game {
    void initialize() {
        System.out.println("初始化板球游戏");
    }
    
    void startPlay() {
        System.out.println("开始板球游戏");
    }
    
    void endPlay() {
        System.out.println("结束板球游戏");
    }
}

// 使用示例
Game game = new Cricket();
game.play(); // 输出: 初始化板球游戏 开始板球游戏 结束板球游戏
11. 访问者模式
  • 特点:表示一个作用于某对象结构中的各元素的操作
  • 生活例子:医生问诊、税务审计
  • 应用场景:需要对对象结构进行操作
  • 代码示例:
java 复制代码
interface Visitor {
    void visit(Element element);
}

interface Element {
    void accept(Visitor visitor);
}

class ConcreteElement implements Element {
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}

class ConcreteVisitor implements Visitor {
    public void visit(Element element) {
        System.out.println("访问元素");
    }
}

// 使用示例
Element element = new ConcreteElement();
Visitor visitor = new ConcreteVisitor();
element.accept(visitor); // 输出: 访问元素

设计原则

1. 单一职责原则(SRP)

  • 一个类应该只有一个引起它变化的原因
  • 生活例子:专业分工、职责明确

2. 开闭原则(OCP)

  • 对扩展开放,对修改关闭
  • 生活例子:模块化设计、可扩展系统

3. 里氏替换原则(LSP)

  • 子类必须能够替换其父类
  • 生活例子:继承关系、类型兼容

4. 接口隔离原则(ISP)

  • 使用多个专门的接口比使用单个总接口要好
  • 生活例子:功能分离、接口精简

5. 依赖倒置原则(DIP)

  • 依赖于抽象而不是具体实现
  • 生活例子:标准化接口、解耦设计

生活中的启示

  1. 模式无处不在:设计模式不仅存在于代码中,更存在于我们的日常生活中

  2. 问题解决之道:每个设计模式都是解决特定问题的最佳实践

  3. 灵活性与可维护性:好的设计模式能够提高系统的灵活性和可维护性

总结

设计模式是软件开发中的宝贵经验,它们源于生活,又服务于生活。通过理解这些模式,我们不仅能够写出更好的代码,还能更好地理解生活中的各种现象和规律。

相关推荐
qqxhb5 小时前
零基础设计模式——总结与进阶 - 3. 学习资源与下一步
学习·设计模式·重构·代码整洁之道
我叫小白菜5 小时前
【Java_EE】设计模式
java·开发语言·设计模式
foDol6 小时前
C++单例模式
c++·单例模式·设计模式
智想天开7 小时前
28.行为型模式分析对比
设计模式
qqxhb8 小时前
零基础设计模式——行为型模式 - 状态模式
java·设计模式·go·状态模式
Dontla9 小时前
C++设计模式分类(GOF-23种设计模式)
开发语言·c++·设计模式
asom229 小时前
设计模式之责任链模式
设计模式·责任链模式
缘友一世9 小时前
java设计模式[4]之设计型模式
java·开发语言·设计模式
charlie11451419118 小时前
从C++编程入手设计模式——外观模式
c++·设计模式·外观模式