首页 > 编程语言 >Java 说一下你熟悉的设计模式?

Java 说一下你熟悉的设计模式?

时间:2024-07-01 09:57:16浏览次数:3  
标签:Java String void Component private class 熟悉 设计模式 public

在 Java 开发中,设计模式是常用的解决方案,用于解决软件设计中的常见问题。以下是一些常用的设计模式:

创建型模式(Creational Patterns)

  1. 单例模式(Singleton Pattern)

    • 确保一个类只有一个实例,并提供一个全局访问点。
    • 示例:
      public class Singleton {
          private static Singleton instance;
      
          private Singleton() {}
      
          public static Singleton getInstance() {
              if (instance == null) {
                  instance = new Singleton();
              }
              return instance;
          }
      }
      
  2. 工厂方法模式(Factory Method Pattern)

    • 定义一个接口用于创建对象,但让子类决定实例化哪个类。
    • 示例:
      public interface Product {
          void use();
      }
      
      public class ConcreteProduct implements Product {
          public void use() {
              System.out.println("Using ConcreteProduct");
          }
      }
      
      public abstract class Creator {
          public abstract Product createProduct();
      }
      
      public class ConcreteCreator extends Creator {
          public Product createProduct() {
              return new ConcreteProduct();
          }
      }
      
  3. 抽象工厂模式(Abstract Factory Pattern)

    • 提供一个接口,用于创建相关或依赖对象的家族,而不指定具体类。
    • 示例:
      public interface AbstractFactory {
          ProductA createProductA();
          ProductB createProductB();
      }
      
      public class ConcreteFactory1 implements AbstractFactory {
          public ProductA createProductA() {
              return new ProductA1();
          }
          public ProductB createProductB() {
              return new ProductB1();
          }
      }
      
  4. 建造者模式(Builder Pattern)

    • 将对象的构建与表示分离,使得同样的构建过程可以创建不同的表示。
    • 示例:
      public class Product {
          private String part1;
          private String part2;
      
          public void setPart1(String part1) {
              this.part1 = part1;
          }
      
          public void setPart2(String part2) {
              this.part2 = part2;
          }
      }
      
      public abstract class Builder {
          protected Product product = new Product();
      
          public abstract void buildPart1();
          public abstract void buildPart2();
      
          public Product getResult() {
              return product;
          }
      }
      
      public class ConcreteBuilder extends Builder {
          public void buildPart1() {
              product.setPart1("Part1");
          }
      
          public void buildPart2() {
              product.setPart2("Part2");
          }
      }
      
  5. 原型模式(Prototype Pattern)

    • 用于创建重复对象,同时又能保证性能。
    • 示例:
      public class Prototype implements Cloneable {
          public Prototype clone() throws CloneNotSupportedException {
              return (Prototype) super.clone();
          }
      }
      

结构型模式(Structural Patterns)

  1. 适配器模式(Adapter Pattern)

    • 将一个类的接口转换成客户希望的另一个接口。
    • 示例:
      public interface Target {
          void request();
      }
      
      public class Adaptee {
          public void specificRequest() {
              System.out.println("Specific request");
          }
      }
      
      public class Adapter implements Target {
          private Adaptee adaptee;
      
          public Adapter(Adaptee adaptee) {
              this.adaptee = adaptee;
          }
      
          public void request() {
              adaptee.specificRequest();
          }
      }
      
  2. 桥接模式(Bridge Pattern)

    • 将抽象部分与它的实现部分分离,使它们都可以独立地变化。
    • 示例:
      public abstract class Abstraction {
          protected Implementor implementor;
      
          protected Abstraction(Implementor implementor) {
              this.implementor = implementor;
          }
      
          public abstract void operation();
      }
      
      public interface Implementor {
          void operationImpl();
      }
      
      public class ConcreteImplementorA implements Implementor {
          public void operationImpl() {
              System.out.println("ConcreteImplementorA operation");
          }
      }
      
      public class RefinedAbstraction extends Abstraction {
          public RefinedAbstraction(Implementor implementor) {
              super(implementor);
          }
      
          public void operation() {
              implementor.operationImpl();
          }
      }
      
  3. 组合模式(Composite Pattern)

    • 允许你将对象组合成树形结构来表现"整体/部分"层次结构。
    • 示例:
      public abstract class Component {
          public void add(Component component) {}
          public void remove(Component component) {}
          public Component getChild(int i) {
              return null;
          }
          public abstract void operation();
      }
      
      public class Leaf extends Component {
          public void operation() {
              System.out.println("Leaf operation");
          }
      }
      
      public class Composite extends Component {
          private List<Component> children = new ArrayList<>();
      
          public void add(Component component) {
              children.add(component);
          }
      
          public void remove(Component component) {
              children.remove(component);
          }
      
          public Component getChild(int i) {
              return children.get(i);
          }
      
          public void operation() {
              for (Component child : children) {
                  child.operation();
              }
          }
      }
      
  4. 装饰模式(Decorator Pattern)

    • 动态地给对象添加一些额外的职责。
    • 示例:
      public interface Component {
          void operation();
      }
      
      public class ConcreteComponent implements Component {
          public void operation() {
              System.out.println("ConcreteComponent operation");
          }
      }
      
      public class Decorator implements Component {
          protected Component component;
      
          public Decorator(Component component) {
              this.component = component;
          }
      
          public void operation() {
              component.operation();
          }
      }
      
      public class ConcreteDecorator extends Decorator {
          public ConcreteDecorator(Component component) {
              super(component);
          }
      
          public void operation() {
              super.operation();
              addedBehavior();
          }
      
          public void addedBehavior() {
              System.out.println("ConcreteDecorator added behavior");
          }
      }
      
  5. 外观模式(Facade Pattern)

    • 提供一个统一的接口,用来访问子系统中的一群接口。
    • 示例:
      public class Facade {
          private Subsystem1 subsystem1 = new Subsystem1();
          private Subsystem2 subsystem2 = new Subsystem2();
      
          public void operation() {
              subsystem1.operation();
              subsystem2.operation();
          }
      }
      
      public class Subsystem1 {
          public void operation() {
              System.out.println("Subsystem1 operation");
          }
      }
      
      public class Subsystem2 {
          public void operation() {
              System.out.println("Subsystem2 operation");
          }
      }
      
  6. 享元模式(Flyweight Pattern)

    • 使用共享对象来减少内存消耗。
    • 示例:
      public class Flyweight {
          private String intrinsicState;
      
          public Flyweight(String intrinsicState) {
              this.intrinsicState = intrinsicState;
          }
      
          public void operation(String extrinsicState) {
              System.out.println("Intrinsic State = " + intrinsicState + ", Extrinsic State = " + extrinsicState);
          }
      }
      
      public 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);
          }
      }
      
  7. 代理模式(Proxy Pattern)

    • 为其他对象提供一种代理以控制对这个对象的访问。
    • 示例:
      public interface Subject {
          void request();
      }
      
      public class RealSubject implements Subject {
          public void request() {
              System.out.println("RealSubject request");
          }
      }
      
      public class Proxy implements Subject {
          private RealSubject realSubject;
      
          public void request() {
              if (realSubject == null) {
                  realSubject = new RealSubject();
              }
              realSubject.request();
          }
      }
      

行为型模式(Behavioral Patterns)

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

    • 为请求创建一个处理链。
    • 示例:
      public abstract class Handler {
          protected Handler successor;
      
          public void setSuccessor(Handler successor) {
              this.successor = successor;
          }
      
          public abstract void handleRequest(String request);
      }
      
      public class ConcreteHandler1 extends Handler {
          public void handleRequest(String request) {
              if (request.equals("Request1")) {
                  System.out.println("ConcreteHandler1 handled the request");
              } else if (successor != null) {
                  successor.handleRequest(request);
              }
          }
      }
      
      public class ConcreteHandler2 extends Handler {
          public void handleRequest(String request) {
              if (request.equals("Request2")) {
                  System.out.println("ConcreteHandler2 handled the request");
              } else if (successor != null) {
                  successor.handleRequest(request);
              }
          }
      }
      
  2. 命令模式(Command Pattern)

    • 将请求封装成对象,从而使您可以用不同的请求对客户进行参数化。
// 定义命令接口
public interface Command {
    void execute();
}

// 具体命令类
public class ConcreteCommand implements Command {
    private Receiver receiver;

    public ConcreteCommand(Receiver receiver) {
        this.receiver = receiver;
    }

    public void execute() {
        receiver.action();
    }
}

// 接收者类
public class Receiver {
    public void action() {
        System.out.println("Receiver is performing an action");
    }
}

// 调用者类
public class Invoker {
    private Command command;

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

    public void executeCommand() {
        command.execute();
    }
}

// 测试类
public class CommandPatternExample {
    public static void main(String[] args) {
        Receiver receiver = new Receiver();
        Command command = new ConcreteCommand(receiver);
        Invoker invoker = new Invoker();

        invoker.setCommand(command);
        invoker.executeCommand();
    }
}

在这个例子中:

  • Command 接口定义了命令的执行方法 execute()
  • ConcreteCommandCommand 接口的具体实现,持有一个 Receiver 实例用于执行具体操作。
  • Receiver 类执行实际的操作。
  • Invoker 类持有一个 Command 对象,并在适当的时候调用 Commandexecute() 方法。
  • CommandPatternExample 类展示了如何使用命令模式:创建 ReceiverConcreteCommandInvoker 对象,并将命令分派给调用者执行。

这个例子演示了命令模式如何将请求封装成对象,从而使得请求的发送者和接收者解耦,同时支持撤销和重做操作。

  1. 解释器模式(Interpreter Pattern)

    • 给定一个语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子。
    • 示例:
      public interface Expression {
          int interpret();
      }
      
      public class NumberExpression implements Expression {
          private int number;
      
          public NumberExpression(int number) {
              this.number = number;
          }
      
          public int interpret() {
              return number;
          }
      }
      
      public class AddExpression implements Expression {
          private Expression left;
          private Expression right;
      
          public AddExpression(Expression left, Expression right) {
              this.left = left;
              this.right = right;
          }
      
          public int interpret() {
              return left.interpret() + right.interpret();
          }
      }
      
  2. 迭代器模式(Iterator Pattern)

    • 提供一种方法顺序访问一个聚合对象中的各个元素,而不暴露其内部表示。
    • 示例:
      public interface Iterator<T> {
          boolean hasNext();
          T next();
      }
      
      public interface Aggregate {
          Iterator<String> createIterator();
      }
      
      public class ConcreteAggregate implements Aggregate {
          private String[] items = {"A", "B", "C"};
      
          public Iterator<String> createIterator() {
              return new ConcreteIterator(items);
          }
      }
      
      public class ConcreteIterator implements Iterator<String> {
          private String[] items;
          private int position = 0;
      
          public ConcreteIterator(String[] items) {
              this.items = items;
          }
      
          public boolean hasNext() {
              return position < items.length;
          }
      
          public String next() {
              return items[position++];
          }
      }
      
  3. 中介者模式(Mediator Pattern)

    • 用一个中介对象来封装一系列的对象交互。
    • 示例:
      public interface Mediator {
          void notify(Component sender, String event);
      }
      
      public class ConcreteMediator implements Mediator {
          private Component component1;
          private Component component2;
      
          public void setComponent1(Component component1) {
              this.component1 = component1;
          }
      
          public void setComponent2(Component component2) {
              this.component2 = component2;
          }
      
          public void notify(Component sender, String event) {
              if (sender == component1) {
                  component2.handleEvent(event);
              } else if (sender == component2) {
                  component1.handleEvent(event);
              }
          }
      }
      
      public abstract class Component {
          protected Mediator mediator;
      
          public Component(Mediator mediator) {
              this.mediator = mediator;
          }
      
          public abstract void handleEvent(String event);
      }
      
      public class ConcreteComponent1 extends Component {
          public ConcreteComponent1(Mediator mediator) {
              super(mediator);
          }
      
          public void handleEvent(String event) {
              System.out.println("ConcreteComponent1 handled event: " + event);
              mediator.notify(this, event);
          }
      }
      
      public class ConcreteComponent2 extends Component {
          public ConcreteComponent2(Mediator mediator) {
              super(mediator);
          }
      
          public void handleEvent(String event) {
              System.out.println("ConcreteComponent2 handled event: " + event);
              mediator.notify(this, event);
          }
      }
      
  4. 备忘录模式(Memento Pattern)

    • 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
    • 示例:
      public class Memento {
          private String state;
      
          public Memento(String state) {
              this.state = state;
          }
      
          public String getState() {
              return state;
          }
      }
      
      public 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();
          }
      }
      
      public class Caretaker {
          private Memento memento;
      
          public void setMemento(Memento memento) {
              this.memento = memento;
          }
      
          public Memento getMemento() {
              return memento;
          }
      }
      
  5. 观察者模式(Observer Pattern)

    • 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动更新。
    • 示例:
      public interface Observer {
          void update(String message);
      }
      
      public interface Subject {
          void registerObserver(Observer observer);
          void removeObserver(Observer observer);
          void notifyObservers(String message);
      }
      
      public class ConcreteSubject implements Subject {
          private List<Observer> observers = new ArrayList<>();
      
          public void registerObserver(Observer observer) {
              observers.add(observer);
          }
      
          public void removeObserver(Observer observer) {
              observers.remove(observer);
          }
      
          public void notifyObservers(String message) {
              for (Observer observer : observers) {
                  observer.update(message);
              }
          }
      }
      
      public class ConcreteObserver implements Observer {
          public void update(String message) {
              System.out.println("Received message: " + message);
          }
      }
      
  6. 状态模式(State Pattern)

    • 允许对象在内部状态改变时改变它的行为,对象看起来似乎修改了它的类。
    • 示例:
      public interface State {
          void handle();
      }
      
      public class ConcreteStateA implements State {
          public void handle() {
              System.out.println("Handling with State A");
          }
      }
      
      public class ConcreteStateB implements State {
          public void handle() {
              System.out.println("Handling with State B");
          }
      }
      
      public class Context {
          private State currentState;
      
          public void setState(State state) {
              this.currentState = state;
          }
      
          public void request() {
              currentState.handle();
          }
      }
      

这些设计模式在 Java 开发中广泛应用,通过不同的模式可以解决各种不同的设计问题,提高代码的灵活性、可维护性和可扩展性。

标签:Java,String,void,Component,private,class,熟悉,设计模式,public
From: https://blog.csdn.net/weixin_45990682/article/details/140093097

相关文章

  • 千万别忽视基础!十张图带你一步步理解Java内存结构!
    作为一个Java程序员,在日常的开发中,不必像C/C++程序员那样,为每一个内存的分配而操心,JVM会替我们进行自动的内存分配和回收,方便我们开发。但是一旦发生内存泄漏或者内存溢出,如果对Java内存结构不清楚,那将会是一件非常麻烦的事情!本文笔者将为大家详解Java内存结构。面试tips聊聊......
  • 基于JAVA的学生信息管理系统设计(答辩稿)
    基于JAVA的学生信息管理系统设计目录一、选题背景及意义1二、国内外研究现状22.1国内研究现状22.2国外研究现状2三、研究主要内容2四、功能设计34.1学生用户功能34.2教师用户功能34.3管理员用户功能34.4数据库设计4五、系统实现5六、总结8参考文......
  • 基于JAVA的学生信息管理系统设计
    目录摘要IIIABSTRACTIV1绪论11.1选题背景及意义11.1.1选题背景11.1.2选题意义11.2国内外研究现状及发展趋势21.2.1国内研究现状21.2.2国外研究现状21.2.3发展趋势21.3研究主要内容32相关技术概论52.1JavaWeb52.2Hibernate52.3MYSQL72......
  • Java助力加固Excel文件,保障数据安全
    前言Excel文件保护是常用的一种功能,文件保护主要有三种:添加密码,如果没有密码不允许打开文件。添加密码,如果没有密码,不能修改文件,但可以打开,只读以及另存文件。只读推荐,通常推荐打开Excel文件的用户使用只读模式打开,这种方式仅是一种提示,并非强行保护文件。给Excel添加保护......
  • Java-HashMap和ConcurrentHashMap的区别
    Java-HashMap和ConcurrentHashMap的区别一、关键区别1.数据结构2.线程安全3.性能4.扩容机制二、源码简析1.并发控制机制2.数据结构转换:链表转红黑树3.扩容机制触发hashMap和concurentHashMap扩容机制的条件三、putIfAbsent方法computeIfAbsent方法区别​在Java......
  • Java方法递归:File文件搜索
        在Java中,方法递归是一种特殊的情况,其中方法直接或间接地调用自身。为了使用方法递归,方法需要有基本情况,即不再调用自身的条件,以防止进入无限循环。    我们来做一个搜索文件并打开的案例。以打开QQ为例,因为我的电脑只有C盘,我搜索文件的地方,就写C盘。publ......
  • Java集成框架
    Java集成框架(JavaIntegrationFramework)涵盖了许多库和工具,帮助开发者实现各种功能。这些框架包括Spring、ApacheCamel、JavaEE等。1.SpringFrameworkSpring是一个广泛使用的企业级应用程序框架,提供全面的基础设施支持,包括依赖注入、面向切面编程、事务管理等教程......
  • 494.力扣每日一题6/30 Java(三种解法)
    博客主页:音符犹如代码系列专栏:算法练习关注博主,后期持续更新系列文章如果有错误感谢请大家批评指出,及时修改感谢大家点赞......
  • “Java编程学习路线图:从新手到专家的全面指南“
    学习Java编程语言是一个系统化的过程,涉及多个阶段和技能点。下面是一个推荐的Java学习路线,包括一些关键的里程碑和相应的表情符号来表达学习过程中的情感体验。1.基础入门......
  • Java毕业设计-高校学生课堂考勤打卡系统 Vue前后端分离
    传统信息的管理大部分依赖于管理人员的手工登记与管理,然而,随着近些年信息技术的迅猛发展,让许多比较老套的信息管理模式进行了更新迭代,班级信息因为其管理内容繁杂,管理数量繁多导致手工进行处理不能满足广大用户的需求,因此就应运而生出相应的高校学生课堂考勤系统。......