百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

工作中最常用的 8 种设计模式(工作中用到的设计模式)

yuyutoo 2025-07-06 17:44 4 浏览 0 评论

前言

设计模式在我们日常的软件开发中无处不在,它们帮助我们编写更易扩展、更具可读性的代码。

今天结合我实际工作场景和源码实例,跟大家一起聊聊工作中最常用的8种设计模式,希望对你会有所帮助。

1. 单例模式

单例模式确保一个类只有一个实例,通常用于管理共享资源,如配置、缓存、线程池等。

代码实现:双重检查锁
这是单例模式的标准写法,既保证线程安全,又避免性能损耗。

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;
    }
}

JDK 中的应用:

  • java.lang.Runtime.getRuntime()
  • java.util.logging.Logger

Spring 中的应用:
Spring 的 Bean 默认是单例模式。可以通过 @Scope("prototype") 将其改为多例。

2. 工厂模式

工厂模式用于封装对象的创建逻辑,特别是当类实例化过程复杂时,可以降低耦合度。

代码实现:简单工厂
以支付系统为例,不同支付方式需要不同的对象。

public class PaymentFactory {
    public static Payment createPayment(String type) {
        switch (type) {
            case "AliPay":
                return new AliPay();
            case "WeChatPay":
                return new WeChatPay();
            default:
                throw new IllegalArgumentException("Unknown payment type");
        }
    }
}

JDK 中的应用:

  • java.util.Calendar.getInstance()
  • javax.xml.parsers.DocumentBuilderFactory.newInstance()

Spring 中的应用:

  • BeanFactory 和 ApplicationContext 都是工厂模式的体现。

3. 策略模式

策略模式将不同算法封装为独立类,并允许在运行时选择不同的策略。

代码实现:促销策略
以电商促销为例,支持满减、打折等多种策略。

public interface PromotionStrategy {
    void applyPromotion();
}

public class DiscountStrategy implements PromotionStrategy {
    @Override
    public void applyPromotion() {
        System.out.println("Applying discount...");
    }
}

public class PromotionContext {
    private PromotionStrategy strategy;

    public PromotionContext(PromotionStrategy strategy) {
        this.strategy = strategy;
    }

    public void executePromotion() {
        strategy.applyPromotion();
    }
}

JDK 中的应用:

  • java.util.Comparator 是典型的策略模式。

Spring 中的应用:

  • 事务管理(TransactionManager),支持编程式和声明式事务。

4. 代理模式

代理模式通过代理对象控制对目标对象的访问,常用于权限控制、日志记录等场景。

代码实现:静态代理
模拟对一个服务的权限控制。

public interface Service {
    void execute();
}

public class RealService implements Service {
    @Override
    public void execute() {
        System.out.println("Executing real service...");
    }
}

public class ServiceProxy implements Service {
    private RealService realService;

    @Override
    public void execute() {
        System.out.println("Checking permissions...");
        if (realService == null) {
            realService = new RealService();
        }
        realService.execute();
    }
}

JDK 中的应用:

  • 动态代理 java.lang.reflect.Proxy
  • RMI(远程方法调用)

Spring 中的应用:

  • AOP(面向切面编程)广泛使用代理模式。

5. 观察者模式

观察者模式定义一对多的依赖,当一个对象状态变化时,所有依赖它的对象都会收到通知。

代码实现:事件通知
模拟微博用户的粉丝通知。

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

public class User implements Observer {
    private String name;

    public User(String name) {
        this.name = name;
    }

    @Override
    public void update(String message) {
        System.out.println(name + " received message: " + message);
    }
}

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

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

    public void post(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}

JDK 中的应用:

  • java.util.Observer 和 java.util.Observable
  • javax.swing.event.ChangeListener

Spring 中的应用:

  • ApplicationEvent 和 ApplicationListener 是典型实现。

6. 装饰器模式

装饰器模式在不改变原始类的基础上,动态扩展其功能。

代码实现:咖啡加料
模拟一个咖啡订单系统,可以动态加料。

public interface Coffee {
    String getDescription();
    double getCost();
}

public class SimpleCoffee implements Coffee {
    @Override
    public String getDescription() {
        return "Simple Coffee";
    }

    @Override
    public double getCost() {
        return 5.0;
    }
}

public class MilkDecorator implements Coffee {
    private Coffee coffee;

    public MilkDecorator(Coffee coffee) {
        this.coffee = coffee;
    }

    @Override
    public String getDescription() {
        return coffee.getDescription() + ", Milk";
    }

    @Override
    public double getCost() {
        return coffee.getCost() + 1.5;
    }
}

JDK 中的应用:

  • java.io.BufferedInputStream 和 java.io.BufferedOutputStream

Spring 中的应用:

  • BeanPostProcessor 用于动态修改 Bean 的行为。

7. 模板方法模式

模板方法模式定义一个算法的骨架,把具体的实现留给子类。

代码实现:任务执行模板
模拟定时任务的执行流程。

public abstract class Task {
    public final void execute() {
        init();
        doWork();
        cleanup();
    }

    protected abstract void init();
    protected abstract void doWork();
    protected void cleanup() {
        System.out.println("Default cleanup...");
    }
}

public class DataProcessingTask extends Task {
    @Override
    protected void init() {
        System.out.println("Initializing data...");
    }

    @Override
    protected void doWork() {
        System.out.println("Processing data...");
    }
}

JDK 中的应用:

  • java.util.AbstractList 和 java.util.AbstractMap

Spring 中的应用:

  • JdbcTemplate 和 RestTemplate

8. 建造者模式

建造者模式用于创建复杂对象,特别是当对象有多个可选参数时。

代码实现:构建 HTTP 请求

public class HttpRequest {
    private String method;
    private String url;
    private String body;

    private HttpRequest(Builder builder) {
        this.method = builder.method;
        this.url = builder.url;
        this.body = builder.body;
    }

    public static class Builder {
        private String method;
        private String url;
        private String body;

        public Builder method(String method) {
            this.method = method;
            return this;
        }

        public Builder url(String url) {
            this.url = url;
            return this;
        }

        public Builder body(String body) {
            this.body = body;
            return this;
        }

        public HttpRequest build() {
            return new HttpRequest(this);
        }
    }
}

JDK 中的应用:

  • StringBuilder
  • Stream.Builder

Spring 中的应用:

  • UriComponentsBuilder 用于构建 URI。

总结

这些设计模式不仅在日常开发中有着广泛应用,更在 JDK 和 Spring 中深度体现。

了解它们的本质和应用场景,能够让我们写出更优雅、更健壮的代码。

下次再遇到类似问题时,希望你能得心应手地选择合适的模式!


来源:
https://mp.weixin.qq.com/s/yp1wtCgILZ9KJ5ObHGWsjg

相关推荐

.NET 奇葩问题调试经历之3——使用了grpc通讯类库后,内存一直增长......

...

全局和隐式 using 指令详解(全局命令)

1.什么是全局和隐式using?在.NET6及更高版本中,Microsoft引入了...

请停止微服务,做好单体的模块化才是王道:Spring Modulith介绍

1、介绍模块化单体是一种架构风格,代码是根据模块的概念构成的。对于许多组织而言,模块化单体可能是一个很好的选择。它有助于保持一定程度的独立性,这有助于我们在需要的时候轻松过渡到微服务架构。Spri...

ASP.NET程序集引用之痛:版本冲突、依赖地狱等解析与实战

我是一位多年后端经验的工程师,其中前几年用ASP.NET...

.NET AOT 详解(.net 6 aot)

简介AOT(Ahead-Of-TimeCompilation)是一种将代码直接编译为机器码的技术,与传统的...

一款基于Yii2开发的免费商城系统(一款基于yii2开发的免费商城系统是什么)

哈喽,我是老鱼,一名致力于在技术道路上的终身学习者、实践者、分享者!...

asar归档解包(游戏arc文件解包)

要学习Electron逆向,首先要有一个Electron开发的程序的发布的包,这里就以其官方的electron-quick-start作为例子来进行一下逆向的过程。...

在PyCharm 中免费集成Amazon CodeWhisperer

CodeWhisperer是Amazon发布的一款免费的AI编程辅助小工具,可在你的集成开发环境(IDE)中生成实时单行或全函数代码建议,帮助你快速构建软件。简单来说,AmazonCodeWhi...

2014年最优秀JavaScript编辑器大盘点

1.WebstormWebStorm是一种轻量级的、功能强大的IDE,为Node.js复杂的客户端开发和服务器端开发提供完美的解决方案。WebStorm的智能代码编辑器支持JavaScript,...

基于springboot、tio、oauth2.0前端vuede 超轻量级聊天软件分享

项目简介:基于JS的超轻量级聊天软件。前端:vue、iview、electron实现的PC桌面版聊天程序,主要适用于私有云项目内部聊天,企业内部管理通讯等功能,主要通讯协议websocket。支持...

JetBrains Toolbox推出全新产品订阅授权模式

捷克知名软件开发公司JetBrains最为人所熟知的产品是Java编程语言开发撰写时所用的集成开发环境IntelliJIDEA,相信很多开发者都有所了解。而近期自2015年11月2日起,JetBr...

idea最新激活jetbrains-agent.jar包,亲测有效

这里分享一个2019.3.3版本的jetbrains-agent.jar,亲测有效,在网上找了很多都不能使用,终于找到一个可以使用的了,这里分享一下具体激活步骤,此方法适用于Jebrains家所有产品...

CountDownTimer的理解(countdowntomars)

CountDownTimer是android开发常用的计时类,按照注释中的说明使用方法如下:kotlin:object:CountDownTimer(30000,1000){...

反射为什么性能会很慢?(反射时为什么会越来越长)

1.背景前段时间维护一个5、6年前的项目,项目总是在某些功能使用上不尽人意,性能上总是差一些,仔细过了一下代码发现使用了不少封装好的工具类,工具类里面用了好多的反射,反射会影响到执行效率吗?盲猜了一...

btrace 开源!基于 Systrace 高性能 Trace 工具

介绍btrace(又名RheaTrace)是抖音基础技术团队自研的一款高性能AndroidTrace工具,它基于Systrace实现,并针对Systrace不足之处加以改进,核心改进...

取消回复欢迎 发表评论: