程序员必备的十大技能(进阶版)之设计模式与架构思维(一)

简介: 教程来源 https://rvtst.cn/ 本文系统讲解设计模式与架构思维,涵盖SOLID原则、创建型/结构型/行为型模式实战、DDD、分层/六边形/微服务架构等十大维度,助你从写代码进阶到设计系统。

在软件开发的广袤世界中,设计模式与架构思维是区分优秀程序员与普通程序员的重要分水岭。初级程序员关注功能的实现,追求代码“能跑起来”;进阶程序员则追求代码的可读、可维护、可扩展;而高级程序员与架构师,则在系统层面思考如何应对需求变化、如何控制复杂度、如何平衡成本与收益。

设计模式不是“银弹”,它是前人总结的针对特定问题的可复用解决方案。而架构思维则是在更高的抽象层次上,对系统的组织、结构、行为和演化进行全局性思考。

本文将围绕“设计模式与架构思维”这一核心主题,从设计模式的核心思想、创建型模式深度解析、结构型模式实战应用、行为型模式精讲、架构设计原则、领域驱动设计(DDD)、分层架构与六边形架构、微服务架构模式、架构演进与重构、以及架构师的思考框架十个维度,带你全面掌握从代码级设计到系统级架构的能力。

一、设计模式的核心思想

1.1 为什么需要设计模式?
设计模式的核心价值不在于“用了就是好代码”,而在于提供了经过验证的解决方案,建立了一套通用的设计词汇。

// 不使用设计模式的“面条式”代码
public class PaymentProcessor {
    public void process(String type, double amount, Map<String, Object> params) {
        if ("credit".equals(type)) {
            // 信用卡支付逻辑
            String cardNo = (String) params.get("cardNo");
            String cvv = (String) params.get("cvv");
            // 数十行业务代码...
        } else if ("paypal".equals(type)) {
            // PayPal支付逻辑
            String email = (String) params.get("email");
            // 数十行业务代码...
        } else if ("wechat".equals(type)) {
            // 微信支付逻辑
            // ...
        }
        // 每次增加新支付方式,都需要修改这个类
    }
}

使用设计模式后的重构:

// 使用策略模式后的优雅设计
public interface PaymentStrategy {
    PaymentResult pay(double amount, Map<String, Object> params);
}

@Service
public class CreditCardPayment implements PaymentStrategy {
    @Override
    public PaymentResult pay(double amount, Map<String, Object> params) {
        // 信用卡支付逻辑
        return PaymentResult.success();
    }
}

@Service
public class PayPalPayment implements PaymentStrategy {
    @Override
    public PaymentResult pay(double amount, Map<String, Object> params) {
        // PayPal支付逻辑
        return PaymentResult.success();
    }
}

// 策略上下文
@Component
public class PaymentContext {
    private final Map<String, PaymentStrategy> strategyMap;

    public PaymentContext(List<PaymentStrategy> strategies) {
        this.strategyMap = strategies.stream()
            .collect(Collectors.toMap(
                s -> s.getClass().getAnnotation(Service.class).name(),
                Function.identity()
            ));
    }

    public PaymentResult executePayment(String type, double amount, Map<String, Object> params) {
        PaymentStrategy strategy = strategyMap.get(type);
        if (strategy == null) {
            throw new UnsupportedPaymentException(type);
        }
        return strategy.pay(amount, params);
    }
}

1.2 设计模式的六大原则(SOLID)
image.png

二、创建型模式:对象的创建与生命周期管理

创建型模式关注如何创建对象,在复杂系统中合理的对象创建方式能显著提升代码的灵活性和可维护性。

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

// 1. 饿汉式(线程安全,但可能造成资源浪费)
public class EagerSingleton {
    private static final EagerSingleton INSTANCE = new EagerSingleton();

    private EagerSingleton() {}

    public static EagerSingleton getInstance() {
        return INSTANCE;
    }
}

// 2. 懒汉式 + DCL(双重检查锁,推荐)
public class LazySingleton {
    // volatile防止指令重排序
    private static volatile LazySingleton instance;

    private LazySingleton() {
        // 防止反射调用
        if (instance != null) {
            throw new RuntimeException("Use getInstance() method");
        }
    }

    public static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (LazySingleton.class) {
                if (instance == null) {
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }
}

// 3. 静态内部类(推荐:懒加载 + 线程安全)
public class StaticInnerSingleton {
    private StaticInnerSingleton() {}

    private static class SingletonHolder {
        private static final StaticInnerSingleton INSTANCE = new StaticInnerSingleton();
    }

    public static StaticInnerSingleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

// 4. 枚举单例(最安全,防止反射和序列化破坏)
public enum EnumSingleton {
    INSTANCE;

    public void doSomething() {
        System.out.println("Enum Singleton");
    }
}

// 5. 注册式单例(Spring容器管理)
@Component
public class SpringSingleton {
    // Spring默认以单例方式管理Bean
}

实际应用场景:

配置管理类(Configuration Manager)

数据库连接池

日志记录器

线程池管理器

2.2 工厂模式族
简单工厂(非GoF模式,但常用)

// 简单工厂
public class SimplePaymentFactory {
    public static Payment createPayment(String type) {
        switch (type) {
            case "credit":
                return new CreditCardPayment();
            case "paypal":
                return new PayPalPayment();
            default:
                throw new IllegalArgumentException("Unknown payment type");
        }
    }
}

工厂方法模式

// 产品接口
public interface Button {
    void render();
    void onClick();
}

// 具体产品
public class WindowsButton implements Button {
    @Override
    public void render() {
        System.out.println("Rendering Windows style button");
    }

    @Override
    public void onClick() {
        System.out.println("Windows button clicked");
    }
}

public class MacButton implements Button {
    @Override
    public void render() {
        System.out.println("Rendering Mac style button");
    }

    @Override
    public void onClick() {
        System.out.println("Mac button clicked");
    }
}

// 工厂接口
public interface ButtonFactory {
    Button createButton();
}

// 具体工厂
public class WindowsButtonFactory implements ButtonFactory {
    @Override
    public Button createButton() {
        return new WindowsButton();
    }
}

public class MacButtonFactory implements ButtonFactory {
    @Override
    public Button createButton() {
        return new MacButton();
    }
}

// 使用示例
public class Application {
    private Button button;

    public Application(ButtonFactory factory) {
        this.button = factory.createButton();
    }

    public void run() {
        button.render();
        button.onClick();
    }

    public static void main(String[] args) {
        String os = System.getProperty("os.name");
        ButtonFactory factory = os.contains("Windows") ? new WindowsButtonFactory() : new MacButtonFactory();
        Application app = new Application(factory);
        app.run();
    }
}

抽象工厂模式

// 产品族1:椅子
public interface Chair {
    void sitOn();
}

public class VictorianChair implements Chair {
    @Override
    public void sitOn() {
        System.out.println("Sitting on Victorian chair");
    }
}

public class ModernChair implements Chair {
    @Override
    public void sitOn() {
        System.out.println("Sitting on modern chair");
    }
}

// 产品族2:沙发
public interface Sofa {
    void lieOn();
}

public class VictorianSofa implements Sofa {
    @Override
    public void lieOn() {
        System.out.println("Lying on Victorian sofa");
    }
}

public class ModernSofa implements Sofa {
    @Override
    public void lieOn() {
        System.out.println("Lying on modern sofa");
    }
}

// 抽象工厂
public interface FurnitureFactory {
    Chair createChair();
    Sofa createSofa();
}

// 具体工厂
public class VictorianFurnitureFactory implements FurnitureFactory {
    @Override
    public Chair createChair() {
        return new VictorianChair();
    }

    @Override
    public Sofa createSofa() {
        return new VictorianSofa();
    }
}

public class ModernFurnitureFactory implements FurnitureFactory {
    @Override
    public Chair createChair() {
        return new ModernChair();
    }

    @Override
    public Sofa createSofa() {
        return new ModernSofa();
    }
}

// 客户端代码
public class FurnitureShop {
    private final Chair chair;
    private final Sofa sofa;

    public FurnitureShop(FurnitureFactory factory) {
        this.chair = factory.createChair();
        this.sofa = factory.createSofa();
    }

    public void showRoom() {
        chair.sitOn();
        sofa.lieOn();
    }
}

2.3 建造者模式(Builder)
建造者模式用于创建复杂对象,将对象的构建与表示分离。

// 复杂对象
public class Order {
    private final String orderId;
    private final String userId;
    private final List<String> productIds;
    private final BigDecimal totalAmount;
    private final String shippingAddress;
    private final String couponCode;
    private final String paymentMethod;
    private final LocalDateTime createTime;

    private Order(Builder builder) {
        this.orderId = builder.orderId;
        this.userId = builder.userId;
        this.productIds = builder.productIds;
        this.totalAmount = builder.totalAmount;
        this.shippingAddress = builder.shippingAddress;
        this.couponCode = builder.couponCode;
        this.paymentMethod = builder.paymentMethod;
        this.createTime = builder.createTime;
    }

    // 静态内部Builder
    public static class Builder {
        // 必填参数
        private final String orderId;
        private final String userId;
        private final List<String> productIds;

        // 可选参数
        private BigDecimal totalAmount = BigDecimal.ZERO;
        private String shippingAddress = "";
        private String couponCode = "";
        private String paymentMethod = "credit";
        private LocalDateTime createTime = LocalDateTime.now();

        public Builder(String orderId, String userId, List<String> productIds) {
            this.orderId = orderId;
            this.userId = userId;
            this.productIds = productIds;
        }

        public Builder totalAmount(BigDecimal totalAmount) {
            this.totalAmount = totalAmount;
            return this;
        }

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

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

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

        public Builder createTime(LocalDateTime createTime) {
            this.createTime = createTime;
            return this;
        }

        public Order build() {
            validate();
            return new Order(this);
        }

        private void validate() {
            if (orderId == null || orderId.isEmpty()) {
                throw new IllegalArgumentException("OrderId is required");
            }
            if (userId == null || userId.isEmpty()) {
                throw new IllegalArgumentException("UserId is required");
            }
            if (productIds == null || productIds.isEmpty()) {
                throw new IllegalArgumentException("ProductIds is required");
            }
        }
    }

    // 使用示例
    public static void main(String[] args) {
        Order order = new Order.Builder("ORD-001", "USER-123", List.of("P1", "P2"))
            .totalAmount(new BigDecimal("199.99"))
            .shippingAddress("123 Main St")
            .couponCode("SAVE10")
            .paymentMethod("paypal")
            .build();
    }
}

2.4 原型模式(Prototype)
原型模式通过复制现有对象来创建新对象,避免昂贵的创建过程。

// 可克隆接口
public interface Prototype extends Cloneable {
    Prototype clone();
}

// 具体原型
public class Document implements Prototype {
    private String title;
    private String content;
    private Map<String, String> metadata;
    private Date createdAt;

    public Document(String title, String content) {
        this.title = title;
        this.content = content;
        this.metadata = new HashMap<>();
        this.createdAt = new Date();
    }

    // 深拷贝实现
    @Override
    public Document clone() {
        try {
            Document clone = (Document) super.clone();
            // 深拷贝引用类型
            clone.metadata = new HashMap<>(this.metadata);
            clone.createdAt = (Date) this.createdAt.clone();
            return clone;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }

    // 使用序列化实现深拷贝(另一种方式)
    public Document deepCopyBySerialization() {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            return (Document) ois.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 原型管理器(缓存原型对象)
    public static class DocumentPrototypeManager {
        private static final Map<String, Document> prototypes = new ConcurrentHashMap<>();

        static {
            // 注册原型
            prototypes.put("invoice", new Document("Invoice Template", ""));
            prototypes.put("report", new Document("Report Template", ""));
        }

        public static Document getPrototype(String type) {
            Document prototype = prototypes.get(type);
            return prototype != null ? prototype.clone() : null;
        }
    }
}

来源:
https://uklgy.cn/

相关文章
|
6月前
|
人工智能 搜索推荐 API
Hermes Agent的部署以及API集成教程
Hermes Agent 是 Nous Research 推出的开源自我进化型AI智能体,支持持久记忆、技能自动沉淀与多工具集成;需通过 WSL2 在 Windows 部署,兼容 OpenAI 标准 API。
589 2
|
算法 计算机视觉 网络架构
YOLOv7 | 模型结构与正负样本分配解析
YOLOv7 | 模型结构与正负样本分配解析
2452 0
YOLOv7 | 模型结构与正负样本分配解析
|
6月前
|
JSON Java fastjson
java工具:《json字符串转JavaBean对象》
java工具:《json字符串转JavaBean对象》
434 6
|
6月前
|
JSON 程序员 开发工具
初级程序员实战教程(一)
教程来源 https://zlpow.cn/ 零基础Python入门教程,手把手教环境搭建、语法详解与实战开发。含300+行可运行代码及详细注释,涵盖变量、函数、OOP、调试测试、Git等核心内容,并完成通讯录与学生成绩系统两大项目。
|
6月前
|
IDE Java 编译器
当 Maven 的 <phase>none</phase> 遇上 VSCode: JDK 版本识别失灵之谜
VSCode打开Spring AI Alibaba项目时,IDE错误识别JDK为1.8而非pom.xml配置的Java 17,导致record等语法报红。根本原因是M2E插件仅识别maven-compiler-plugin的default-compile执行,而项目禁用了该执行且使用自定义ID,致编译配置无法提取。
|
6月前
|
Arthas 缓存 安全
【Java并发编程】高频实战:死锁排查、线程安全问题定位、线程dump分析(附《思维导图》+《面试高频考点清单》)
本文系统梳理Java并发编程高频实战知识:涵盖死锁排查(Coffman四条件、jstack/Arthas分析)、线程安全定位(竞态/可见性/有序性问题及原子类、Lock、ThreadLocal等方案)与线程Dump深度解析(状态识别、死锁/锁竞争/死循环模式)。
|
7月前
|
前端开发 JavaScript 程序员
初级程序员必备的十大技能之开发工具熟练使用(三)
教程来源 https://bncne.cn/ 浏览器开发者工具是前端调试核心利器,涵盖Elements(实时编辑DOM/CSS)、Console(日志、断点、DOM操作)、Sources(多类型断点与作用域调试)、Network(请求分析与模拟)、Performance(性能指标与火焰图)及Application(存储管理)六大面板,全面提升开发效率。
|
8月前
|
运维 数据库 数据安全/隐私保护
【微服务】微服务 vs 单体架构 区别、服务拆分原则、DDD领域驱动设计
本文构建“架构对比→拆分准则→DDD方法论→落地实践→避坑指南”闭环体系,系统剖析单体与微服务的本质差异、演进路径及反模式;详解微服务拆分八大原则与六大禁忌;深度整合DDD战略设计(限界上下文即服务边界)与战术设计(四层架构+聚合建模),提供从0到1的渐进式落地路径与各阶段最佳实践。
1231 1
|
6月前
|
存储 弹性计算 安全
跨境独立站轻量化上云与高可用架构实践
Taoify是国产零代码跨境建站SaaS,深度集成阿里云:1小时极速上线,CDN全球加速保障海外访问,WAF+SSL+TDE全链路安全合规,弹性扩缩容应对大促峰值。轻量部署、开放API、多语言/汇率/SEO一体化,助力中小商家低成本打造高可用独立站。(239字)
|
6月前
|
设计模式 架构师 程序员
程序员必备的十大技能(进阶版)之设计模式与架构思维(五)
教程来源 https://xgmoi.cn/ DDD是应对复杂业务的架构方法论,含战略设计(限界上下文、上下文映射、子域划分)与战术设计(实体、值对象、聚合根、领域服务等),强调以领域模型驱动开发,实现业务与技术深度对齐。