Java学习第五十八部分——设计模式

目录

一、概述提要

二、创建型模式—— 解决“如何创建对象”的问题

1. 单例模式 (Singleton)

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

3. 解释器模式 (Interpreter) 

4. 建造者模式 (Builder)  

5. 原型模式 (Prototype)  

三、结构型模式——解决“如何组合类和对象”的问题

1. 适配器模式 (Adapter)  

2. 桥接模式 (Bridge)  

3. 组合模式 (Composite)  

4. 装饰器模式 (Decorator)  

5. 外观模式 (Facade)  

6. 享元模式 (Flyweight)  

7. 代理模式 (Proxy)

四、行为型模式——解决“对象之间如何交互和分配职责”的问题

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

2. 命令模式 (Command)  

3. 解释器模式 (Interpreter)

4. 迭代器模式 (Iterator)

5. 中介者模式 (Mediator)

6. 备忘录模式 (Memento)

7. 观察者模式 (Observer)

8. 状态模式 (State)

9. 策略模式 (Strategy)

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

11. 访问者模式 (Visitor)

五、有利因素

六、设计原则

七、核心思想

八、一句话总结


一、概述提要

       Java设计模式是解决软件设计中常见问题的可重用方案,分为三大类:创建型、结构型和行为型。设计模式是软件设计中针对常见问题的、经过验证的、最佳实践的“模板”或“套路”。 它们不是现成的代码,而是解决特定类型问题的成熟思路和结构。

二、创建型模式—— 解决“如何创建对象”的问题

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 Product { void use(); }
   class ConcreteProduct implements Product {
       @Override public void use() { System.out.println("使用具体产品"); }
   }
   abstract class Creator {
       public abstract Product factoryMethod();
   }
   class ConcreteCreator extends Creator {
       @Override public Product factoryMethod() { return new ConcreteProduct(); }
   }

3. 解释器模式 (Interpreter) 

- 创建相关或依赖对象的家族,无需指定具体类。  

   interface GUIFactory { Button createButton(); }
   class WinFactory implements GUIFactory {
       @Override public Button createButton() { return new WinButton(); }
   }
   interface Button { void render(); }
   class WinButton implements Button {
       @Override public void render() { System.out.println("Windows 按钮"); }
   }

4. 建造者模式 (Builder)  

   - 分步构建复杂对象。  

   class Product { private String part; public void setPart(String part) { this.part = part; } }
   interface Builder { void buildPart(); Product getResult(); }
   class ConcreteBuilder implements Builder {
       private Product product = new Product();
       @Override public void buildPart() { product.setPart("组件"); }
       @Override public Product getResult() { return product; }
   }

5. 原型模式 (Prototype)  

   - 通过复制现有对象创建新对象。  

   class Prototype implements Cloneable {
       @Override public Prototype clone() throws CloneNotSupportedException {
           return (Prototype) super.clone();
       }
   }

三、结构型模式——解决“如何组合类和对象”的问题

1. 适配器模式 (Adapter)  

   - 转换接口使不兼容的类能协作。  

   class Adaptee { void specificRequest() { System.out.println("特殊请求"); } }
   interface Target { void request(); }
   class Adapter implements Target {
       private Adaptee adaptee;
       public Adapter(Adaptee adaptee) { this.adaptee = adaptee; }
       @Override public void request() { adaptee.specificRequest(); }
   }

2. 桥接模式 (Bridge)  

   - 分离抽象与实现,使二者独立变化。  

   interface Implementor { void operationImpl(); }
   class ConcreteImplementor implements Implementor {
       @Override public void operationImpl() { System.out.println("具体实现"); }
   }
   abstract class Abstraction {
       protected Implementor impl;
       public Abstraction(Implementor impl) { this.impl = impl; }
       public abstract void operation();
   }

3. 组合模式 (Composite)  

   - 以树形结构处理部分-整体关系。  

   interface Component { void operation(); }
   class Leaf implements Component {
       @Override public void operation() { System.out.println("叶子操作"); }
   }
   class Composite implements Component {
       private List children = new ArrayList<>();
       public void add(Component c) { children.add(c); }
       @Override public void operation() { children.forEach(Component::operation); }
   }

4. 装饰器模式 (Decorator)  

   - 动态添加功能。  

   interface Component { void operation(); }
   class ConcreteComponent implements Component {
       @Override public void operation() { System.out.println("基本操作"); }
   }
   abstract class Decorator implements Component {
       protected Component component;
       public Decorator(Component component) { this.component = component; }
   }
   class ConcreteDecorator extends Decorator {
       public ConcreteDecorator(Component c) { super(c); }
       @Override public void operation() { 
           super.operation(); 
           addedBehavior(); 
       }
       private void addedBehavior() { System.out.println("增强功能"); }
   }

5. 外观模式 (Facade)  

   - 为子系统提供统一入口。  

   class SubSystemA { void operationA() { System.out.println("子系统A操作"); } }
   class Facade {
       private SubSystemA a = new SubSystemA();
       public void wrapOperation() { a.operationA(); }
   }

6. 享元模式 (Flyweight)  

   - 共享细粒度对象以减少内存占用。  

   class FlyweightFactory {
       private Map pool = new HashMap<>();
       public Flyweight getFlyweight(String key) {
           if (!pool.containsKey(key)) {
               pool.put(key, new ConcreteFlyweight(key));
           }
           return pool.get(key);
       }
   }

7. 代理模式 (Proxy)

    - 控制对其他对象的访问。 

   interface Subject { void request(); }
   class RealSubject implements Subject {
       @Override public void request() { System.out.println("真实请求"); }
   }
   class Proxy implements Subject {
       private RealSubject realSubject;
       @Override public void request() {
           if (realSubject == null) realSubject = new RealSubject();
           realSubject.request();
       }
   }

四、行为型模式——解决“对象之间如何交互和分配职责”的问题

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

   - 多个对象处理请求,避免耦合。  

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

2. 命令模式 (Command)  

  - 将请求封装为对象。  

   interface Command { void execute(); }
   class Receiver { void action() { System.out.println("执行操作"); } }
   class ConcreteCommand implements Command {
       private Receiver receiver;
       public ConcreteCommand(Receiver r) { this.receiver = r; }
       @Override public void execute() { receiver.action(); }
   }

3. 解释器模式 (Interpreter)

    - 定义语法的表示和解释(如正则表达式)。  

   interface Expression { boolean interpret(String context); }
   class TerminalExpression implements Expression {
       private String data;
       public TerminalExpression(String data) { this.data = data; }
       @Override public boolean interpret(String context) { return context.contains(data); }
   }

4. 迭代器模式 (Iterator)

    - 提供顺序访问聚合对象元素的方法。  

   interface Iterator { boolean hasNext(); T next(); }
   class ConcreteIterator implements Iterator {
       private String[] items;
       private int position = 0;
       public ConcreteIterator(String[] items) { this.items = items; }
       @Override public boolean hasNext() { return position < items.length; }
       @Override public String next() { return items[position++]; }
   }

5. 中介者模式 (Mediator)

     - 封装对象间的交互。  

   class Mediator {
       void send(String message, Colleague colleague) { /* 协调通信 */ }
   }
   abstract class Colleague {
       protected Mediator mediator;
       public Colleague(Mediator m) { this.mediator = m; }
   }

6. 备忘录模式 (Memento)

    - 捕获对象状态以便恢复。  

   class Originator {
       private String state;
       public void setState(String state) { this.state = state; }
       public Memento save() { return new Memento(state); }
       public void restore(Memento m) { state = m.getState(); }
   }
   class Memento {
       private final String state;
       public Memento(String state) { this.state = state; }
       public String getState() { return state; }
   }

7. 观察者模式 (Observer)

    - 对象状态变化时通知依赖对象。  

   interface Observer { void update(); }
   class Subject {
       private List observers = new ArrayList<>();
       public void attach(Observer o) { observers.add(o); }
       public void notifyObservers() { observers.forEach(Observer::update); }
   }

8. 状态模式 (State)

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

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

9. 策略模式 (Strategy)

    - 定义算法族,使其可互换。  

   interface Strategy { void execute(); }
   class Context {
       private Strategy strategy;
       public void setStrategy(Strategy s) { strategy = s; }
       public void executeStrategy() { strategy.execute(); }
   }

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

     - 定义算法骨架,子类重写特定步骤。  

    abstract class AbstractClass {
        public void templateMethod() {
            step1();
            step2();
        }
        protected abstract void step1();
        protected abstract void step2();
    }

11. 访问者模式 (Visitor)

     - 在不修改类的前提下添加新操作。  

    interface Visitor { void visit(Element element); }
    interface Element { void accept(Visitor visitor); }
    class ConcreteElement implements Element {
        @Override public void accept(Visitor v) { v.visit(this); }
    }

五、有利因素

  • 代码复用: 避免重复发明轮子,直接用成熟的方案。

  • 提高可维护性: 代码结构清晰、逻辑分明,更容易理解和修改。

  • 提高扩展性: 更容易添加新功能而不破坏原有代码。

  • 提高灵活性: 让代码更容易适应变化。

  • 团队协作: 提供通用的“设计语言”,方便交流。

六、设计原则

  • 开闭原则:对扩展开放,对修改关闭。  

  • 单一职责:一个类只负责一个功能。  

  • 依赖倒置:依赖抽象而非具体实现。  

  • 接口隔离:使用多个专用接口。  

  • 里氏替换:子类可替代父类。  

  • 迪米特法则:减少对象间耦合。  

七、核心思想

  • 找变化,封装变化: 识别哪些地方容易变,把这些变化点隔离起来(用接口、抽象类等),让它们的变化不影响其他稳定部分。

  • 针对接口编程,而不是实现: 多依赖抽象(接口、抽象类),少依赖具体类,增加灵活性。

  • 组合优于继承: 多用组合(has-a 关系)来扩展功能,少用继承(is-a 关系),避免继承带来的强耦合和复杂性。

  • 高内聚,低耦合: 一个类/模块只做一件事(内聚),类/模块之间尽量少依赖(耦合)。

八、一句话总结

       Java设计模式就是前辈程序员们总结出来的一套解决软件设计中常见难题的“武功秘籍”,学会了它们,你写出来的代码会更健壮、更灵活、更好维护! 不要死记硬背代码,关键是理解其意图和解决的问题场景。

你可能感兴趣的:(java,学习,设计模式)