编程面试的十大设计模式

2025-05-27

编程面试的十大设计模式

披露:本篇文章包含附属链接;如果您通过本文提供的不同链接购买产品或服务,我可能会收到报酬。

10分钟讲解10种设计模式
致谢 -设计模式快速参考,并非常感谢 Jason McDonald 创建了这张出色的备忘单。

大家好,设计模式是人们告诉我要学习成为高级软件工程师的技能之一,因为它在高级软件工程师面试中得到了严格的考验。

当我后来了解到这一点时,我发现设计模式对于编写可以在生产中生存的干净代码是多么重要。

对于那些不知道的人来说,设计模式是针对软件设计中遇到的常见问题的可重复使用的解决方案。

它们概括了最佳实践,并提供了创建灵活、可维护和可扩展的软件的蓝图。

在之前的几篇文章中,我分享了许多流行的系统设计问题,例如API 网关与负载均衡器水平扩展与垂直扩展正向代理与反向代理以及50 个系统设计问题,今天我将分享编程面试的 10 种设计模式。

顺便说一句,如果您还没有读过这些文章,您也可以阅读它们,特别是如果您想学习系统设计,这是高级软件工程师的另一项热门技能。

如果您正在学习这些概念作为面试准备的一部分,那么我还建议您查看ByteByteGo、  DesignGurus.io、  Exponent、  Educative、  Codeemia.io、  InterviewReddy.io 和 Udemy等网站 ,这些网站有许多很棒的系统设计课程

设计模式课程

PS:请坚持读到最后。我有一个福利给你。

编程面试的 10 个基本 OOP 设计模式

因此,这里有 10 个重要的设计模式,你可以在编程工作面试中学习,虽然阅读本文可能需要较少的时间,但如果你想尝试代码示例,可能需要超过 10 分钟,但 10 分钟足以阅读和理解这些代码示例。

1.单例模式

单例模式确保一个类只有一个实例,并提供一个全局访问点。当只需要一个对象来协调整个系统的操作时,这尤其有用。

这是单例模式的代码示例

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
Enter fullscreen mode Exit fullscreen mode

影响
此模式确保特定资源的单点控制,防止不必要的实例化并确保高效的资源利用。

尽管许多人认为 Singleton 是反模式,因为它不易进行单元测试,并且依赖注入比 Singleton 更受欢迎,但它仍然是一种值得了解的好模式。

这是单例模式的 UML 图

单例设计模式


2.工厂方法模式

工厂方法模式定义了一个用于创建对象的接口,但允许子类改变将要创建的对象的类型。

它提供了一个用于创建类实例的接口,由其子类决定实例化哪个类。

以下是此模式的示例代码:


public interface Product {
    void create();
}

public class ConcreteProduct implements Product {
    @Override
    public void create() {
        // Implementation
    }
}

public interface Creator {
    Product factoryMethod();
}

public class ConcreteCreator implements Creator {
    @Override
    public Product factoryMethod() {
        return new ConcreteProduct();
    }
}
Enter fullscreen mode Exit fullscreen mode

影响
这种设计模式允许客户端代码通过接口与对象交互,从而促进松散耦合,使其更易于扩展和维护。

这是工厂方法模式的 UML 图:

工厂方法模式


3.观察者模式

观察者模式定义了对象之间的一对多依赖关系,以便当一个对象改变状态时,其所有依赖者都会得到通知并自动更新。

这通常用于实现分布式事件处理系统。

例子:

public interface Observer {
    void update(String message);
}

public class ConcreteObserver implements Observer {
    @Override\
    public void update(String message) {
        // Implementation
    }
}

public class Subject {
    private List<Observer> observers = new ArrayList<>();

    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

影响
此模式能够明确区分主体和观察者,从而易于扩展和维护。

这是观察者模式的 UML 图:

观察者设计模式


4.策略模式

策略模式定义了一系列算法,并将它们逐一封装,使它们可以互换。它允许客户端在运行时选择合适的算法。

以下是此模式的代码示例:

public interface PaymentStrategy {
    void pay(int amount);
}

public class CreditCardPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        // Implementation
    }
}

public class PayPalPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        // Implementation
    }
}

public class ShoppingCart {
    private PaymentStrategy paymentStrategy;

    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void checkout(int amount) {
        paymentStrategy.pay(amount);
    }
}
Enter fullscreen mode Exit fullscreen mode

影响
这种设计模式允许算法独立于使用它们的客户端而变化,从而提高了算法替换的灵活性和便利性。

下面是 Java 中策略设计模式的 UML 图:

Java中的策略设计模式


5.装饰器模式

装饰器模式动态地为对象附加额外的职责。装饰器提供了一种灵活的替代子类化方法来扩展功能。

例子:

public interface Component {
    void operation();
}

public class ConcreteComponent implements Component {
    @Override
    public void operation() {
        // Implementation
    }
}

public abstract class Decorator implements Component {
    private Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
        component.operation();
    }
}

public class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        // Additional functionality
    }
}
Enter fullscreen mode Exit fullscreen mode

影响
此模式可以动态地向对象添加职责,避免需要大量的子类。

这是装饰器设计模式的UML图:

装饰器设计模式


6.适配器模式

适配器模式允许不兼容的接口协同工作。它充当两个不兼容接口之间的桥梁,使它们在不更改代码的情况下兼容。

下面是 Java 中适配器模式的代码示例:

public interface Target {
    void request();
}

public class Adaptee {
    public void specificRequest() {
        // Implementation
    }
}

public class Adapter implements Target {
    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}
Enter fullscreen mode Exit fullscreen mode

影响
此模式允许现有系统在接口不兼容的情况下协同工作,从而促进现有系统的集成。

下面是 Java 中适配器模式的 UML 图:

Java中的适配器模式


7. 命令模式

命令模式将请求封装为对象,从而允许对具有不同请求的客户端进行参数化、对请求进行排队以及对参数进行记录。

以下是此模式的代码示例:

public interface Command {
    void execute();
}

public class ConcreteCommand implements Command {
    private Receiver receiver;

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

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

public class Receiver {
    public void action() {
        // Implementation
    }
}

public class Invoker {
    private Command command;

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

    public void executeCommand() {
        command.execute();
    }
}
Enter fullscreen mode Exit fullscreen mode

影响
此模式促进了请求的发送者和接收者之间的松散耦合,从而允许命令处理的可扩展性和灵活性。

下面是 Java 中命令模式的 UML 图:

Java中的命令模式


8. 复合模式

组合模式将对象组合成树形结构,以表示部分-整体的层次结构。它允许客户端以统一的方式处理单个对象及其组合对象。

下面是用 Java 实现复合模式的代码示例:

public interface Component {
    void operation();
}

public class Leaf implements Component {
    @Override
    public void operation() {
        // Implementation
    }
}

public class Composite implements Component {
    private List<Component> components = new ArrayList<>();

    public void addComponent(Component component) {
        components.add(component);
    }

    @Override
    public void operation() {
        for (Component component : components) {
            component.operation();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

**影响
**这种模式允许客户端代码统一处理单个对象和组合,从而大大简化了客户端代码。

以下是 Java 中复合模式的 UML 图:

Java中的复合设计模式


9. 责任链模式

责任链模式将请求沿着一系列处理程序传递。每个处理程序决定是处理该请求还是将其传递给链中的下一个处理程序。

以下是此模式的代码示例:

public abstract class Handler {
    private Handler successor;

    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }

    public void handleRequest() {
        if (successor != null) {
            successor.handleRequest();
        }
    }
}

public class ConcreteHandler extends Handler {
    @Override
    public void handleRequest() {
        // Handle the request
        super.handleRequest();
    }
}
Enter fullscreen mode Exit fullscreen mode

影响
此模式将发送者和接收者分离,允许多个对象处理一个请求,而无需发送者知道哪个对象最终将处理它。

以下是 Java 中责任链模式的 UML 图:

责任链模式


10.状态模式

状态模式允许对象在其内部状态改变时改变其行为。对象看起来就像改变了它的类。

以下是 Java 中状态设计模式的代码示例:

public interface State {
    void handle();
}

public class ConcreteStateA implements State {
    @Override
    public void handle() {
        // Implementation for state A
    }
}

public class ConcreteStateB implements State {
    @Override
    public void handle() {
        // Implementation for state B
    }
}

public class Context {
    private State currentState;

    public void setState(State state) {
        currentState = state;
    }

    public void request() {
        currentState.handle();
    }
}
Enter fullscreen mode Exit fullscreen mode

影响
状态设计模式通过允许复杂对象动态地改变其内部状态来简化复杂对象的行为。

以下是 Java 中状态设计模式的 UML 图:

Java中的状态设计模式

结论

以上就是关于编程面试必备的 10 个设计模式的全部内容。设计模式是开发人员工具包中的强大工具,能够为常见的软件设计挑战提供解决方案。

理解和实施这些模式可以显著提高代码的可维护性、可扩展性和可伸缩性。

虽然掌握这些模式可能需要时间,但明智地将它们融入到您的项目中无疑将带来更强大、更灵活的软件架构。

进一步学习

  1. Java 中的设计模式探索 Java 中设计模式的实际实现。
  2. 基础软件架构学习软件架构的基础概念。
  3. 理解 OOP 面试准备使用真实场景的面向对象编程面试。
  4. Java 设计模式和架构(免费)访问 Java 设计模式及其应用的免费指南。
  5. 设计模式库丰富的设计模式示例和解释库。
  6. 通过示例学习模式通过具体示例学习模式以便更好地理解。

奖金

正如承诺的那样,这是给你的福利,一本免费的书。我刚刚找到了一本学习分布式系统设计的免费新书,你也可以在微软官网上阅读——https: //info.microsoft.com/rs/157-GQE-382/images/EN-CNTNT-eBook-DesigningDistributedSystems.pdf

Java中的设计模式

图片来源 --- 推特

文章来源:https://dev.to/somadevtoo/top-10-design-patterns-for-programming-interviews-8j4
PREV
编程面试的 16 个最佳系统设计资源
NEXT
系统设计基础 - 负载平衡算法