在软件开发的广袤世界中,设计模式与架构思维是区分优秀程序员与普通程序员的重要分水岭。初级程序员关注功能的实现,追求代码“能跑起来”;进阶程序员则追求代码的可读、可维护、可扩展;而高级程序员与架构师,则在系统层面思考如何应对需求变化、如何控制复杂度、如何平衡成本与收益。
设计模式不是“银弹”,它是前人总结的针对特定问题的可复用解决方案。而架构思维则是在更高的抽象层次上,对系统的组织、结构、行为和演化进行全局性思考。
本文将围绕“设计模式与架构思维”这一核心主题,从设计模式的核心思想、创建型模式深度解析、结构型模式实战应用、行为型模式精讲、架构设计原则、领域驱动设计(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)
二、创建型模式:对象的创建与生命周期管理
创建型模式关注如何创建对象,在复杂系统中合理的对象创建方式能显著提升代码的灵活性和可维护性。
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;
}
}
}