【学习笔记】Java中常用设计模式有哪些?如何实现

Java 中常用的设计模式主要有以下几种,每种模式都有其特定的应用场景和目的:

  1. 单例模式(Singleton):确保一个类只有一个实例,并提供一个全局访问点。

    • 实现样例:
      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):定义创建对象的接口,让子类决定实例化哪一个类。

    • 实现样例:
      interface Product {
          void use();
      }
      
      class ConcreteProduct implements Product {
          public void use() {
              // 具体实现
          }
      }
      
      abstract class Creator {
          abstract Product factoryMethod();
      }
      
      class ConcreteCreator extends Creator {
          public Product factoryMethod() {
              return new ConcreteProduct();
          }
      }
      
  3. 建造者模式(Builder):用于创建一个复杂对象,同时允许用户只通过指定复杂对象的类型和内容就能构建它们,隐藏了内部的构建细节。

    • 实现样例:
      class Product {
          private String part1;
          private String part2;
          
          public static class Builder {
              private String part1;
              private String part2;
              
              public Builder setPart1(String part1) {
                  this.part1 = part1;
                  return this;
              }
              
              public Builder setPart2(String part2) {
                  this.part2 = part2;
                  return this;
              }
              
              public Product build() {
                  return new Product(this);
              }
          }
          
          private Product(Builder builder) {
              this.part1 = builder.part1;
              this.part2 = builder.part2;
          }
      }
      
  4. 原型模式(Prototype):通过拷贝现有的实例来创建新的实例,而不是通过新建实例。

    • 实现样例:
      interface Prototype {
          Prototype clone();
      }
      
      class ConcretePrototype implements Prototype, Cloneable {
          public Prototype clone() {
              try {
                  return (ConcretePrototype) super.clone();
              } catch (CloneNotSupportedException e) {
                  // 异常处理
                  return null;
              }
          }
      }
      
  5. 适配器模式(Adapter):将一个类的接口转换成客户期望的另一个接口,使原本由于接口不兼容而不能一起工作的类可以一起工作。

    • 实现样例:
      interface Target {
          void request();
      }
      
      class Adaptee {
          public void specificRequest() {
              // 特定实现
          }
      }
      
      class Adapter implements Target {
          private Adaptee adaptee;
          
          public Adapter(Adaptee adaptee) {
              this.adaptee = adaptee;
          }
          
          public void request() {
              adaptee.specificRequest();
          }
      }
      
  6. 装饰器模式(Decorator):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰器模式比生成子类更为灵活。

    • 实现样例:
      interface Component {
          void operate();
      }
      
      class ConcreteComponent implements Component {
          public void operate() {
              // 具体实现
          }
      }
      
      abstract class Decorator implements Component {
          protected Component component;
          
          public Decorator(Component component) {
              this.component = component;
          }
          
          public void operate() {
              component.operate();
          }
      }
      
      class ConcreteDecoratorA extends Decorator {
          public ConcreteDecoratorA(Component component) {
              super(component);
          }
          
          public void operate() {
              super.operate();
              // 额外功能
          }
      }
      
  7. 观察者模式(Observer):对象间的一对多依赖关系,当一个对象改变状态时,所有依赖于它的对象都会得到通知并自动更新。

    • 实现样例:
      interface Subject {
          void registerObserver(Observer o);
          void removeObserver(Observer o);
          void notifyObservers();
      }
      
      interface Observer {
          void update();
      }
      
      class ConcreteSubject implements Subject {
          private List<Observer> observers = new ArrayList<>();
          
          public void registerObserver(Observer o) {
              observers.add(o);
          }
          
          public void removeObserver(Observer o) {
              observers.remove(o);
          }
          
          public void notifyObservers() {
              for (Observer observer : observers) {
                  observer.update();
              }
          }
          
          public void someBusinessLogic() {
              // 业务逻辑
              notifyObservers();
          }
      }
      
      class ConcreteObserver implements Observer {
          public void update() {
              // 更新逻辑
          }
      }
      
  8. 策略模式(Strategy):定义一系列算法,把它们一个个封装起来,并使它们可以互相替换。

    • 实现样例:
      interface Strategy {
          void algorithm();
      }
      
      class ConcreteStrategyA implements Strategy {
          public void algorithm() {
              // 算法A的实现
          }
      }
      
      class Context {
          private Strategy strategy;
          
          public Context(Strategy strategy) {
              this.strategy = strategy;
          }
          
          public void setStrategy(Strategy strategy) {
              this.strategy = strategy;
          }
          
          public void executeStrategy() {
              strategy.algorithm();
          }
      }
      
  9. 命令模式(Command):将请求或操作封装为一个对象,从而允许用户使用不同的请求、队列或日志请求来参数化其他对象。

    • 实现样例:
      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() {
              // 具体实现
          }
      }
      
      class Invoker {
          private Command command;
          
          public void setCommand(Command command) {
              this.command = command;
          }
          
          public void executeCommand() {
              command.execute();
          }
      }
      
  10. 模板方法模式(Template Method):定义一个操作中的算法的框架,而将一些步骤的执行延迟到子类中。

    • 实现样例:
      abstract class AbstractClass {
          public void templateMethod() {
              baseOperation1();
              baseOperation2();
              hook();
          }
          
          protected abstract void baseOperation1();
          protected void baseOperation2() {
              // 基本实现
          }
          
          public void hook() {
              // 子类可以重写
          }
      }
      
      class ConcreteClass extends AbstractClass {
          protected void baseOperation1() {
              // 具体实现
          }
          
          public void hook() {
              // 具体实现
          }
      }
      
  11. 迭代器模式(Iterator):提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。

    • 实现样例:
      interface Iterator {
          boolean hasNext();
          Object next();
      }
      
      interface Aggregate {
          Iterator createIterator();
      }
      
      class ConcreteIterator implements Iterator {
          private ConcreteAggregate aggregate;
          // 迭代器内部状态
          
          public ConcreteIterator(ConcreteAggregate aggregate) {
              this.aggregate = aggregate;
          }
          
          public boolean hasNext() {
              // 检查是否有更多元素
          }
          
          public Object next() {
              // 返回下一个元素
          }
      }
      
      class ConcreteAggregate implements Aggregate {
          private List elements = new ArrayList();
          
          public Iterator createIterator() {
              return new ConcreteIterator(this);
          }
          
          // 聚合类方法
      }
      
  12. 中介者模式(Mediator):用一个中介对象来封装一系列对象之间的交互。

    • 实现样例:
      interface Mediator {
          void register(String colleagueName, Colleague colleague);
          void relay(String colleagueName, String message);
      }
      
      class ConcreteMediator implements Mediator {
          private Map<String, Colleague> colleagues = new HashMap<>();
          
          public void register(String colleagueName, Colleague colleague) {
              colleagues.put(colleagueName, colleague);
          }
          
          public void relay(String colleagueName, String message) {
              Colleague colleague = colleagues.get(colleagueName);
              colleague.receive(message);
          }
      }
      
      interface Colleague {
          void send(String message);
          void receive(String message);
      }
      
      class ConcreteColleagueA implements Colleague {
          private Mediator mediator;
          
          public ConcreteColleagueA(Mediator mediator) {
              this.mediator = mediator;
          }
          
          public void send(String message) {
              mediator.relay("ConcreteColleagueA", message);
          }
          
          public void receive(String message) {
              // 处理消息
          }
      }
      
  13. 备忘录模式(Memento):在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。

    • 实现样例:
      
      
      
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值