优点总结:
缺点总结:
优点总结:
缺点总结:
优点总结:
缺点总结:
阿里电商系统案例:
// 订单建造者示例
public class OrderBuilder {
private String orderId;
private List<OrderItem> items;
private Payment payment;
public OrderBuilder withOrderId(String orderId) {
this.orderId = orderId;
return this;
}
public OrderBuilder withItems(List<OrderItem> items) {
this.items = items;
return this;
}
public Order build() {
// 复杂校验和构建逻辑
return new Order(orderId, items, payment);
}
}
字节跳动推荐系统案例:
// 字节跳动广告投放配置
AdCampaign campaign = new AdCampaignBuilder()
.withName("双十一促销")
.withBudget(100000)
.withTargeting(targeting)
.withCreatives(creatives)
.build();
// 阿里支付路由
PaymentStrategy strategy = PaymentStrategyFactory.getStrategy(paymentType);
strategy.pay(amount);
// 商品库存通知
product.addStockObserver(new InventoryService());
product.addStockObserver(new RecommendationEngine());
product.setStock(100); // 自动通知观察者
电商促销系统案例:
代码实现:
// 策略模式+工厂模式组合
public class PromotionService {
private PromotionStrategyFactory factory;
public Order applyPromotion(Order order, String promotionType) {
PromotionStrategy strategy = factory.createStrategy(promotionType);
return strategy.apply(order);
}
}
服务网格中的模式应用:
趋势分析:
Reactive设计模式:
// 观察者模式的现代化实现
Flux<Order> orders = orderService.getOrders();
orders
.filter(o -> o.getAmount() > 1000)
.map(this::applyDiscount)
.subscribe(this::processOrder);
新兴模式:
ML系统中的设计模式:
创新方向:
问题背景:在快速迭代的互联网项目中,如何平衡设计模式的使用与开发效率?
解决方案:
// 初始简单实现
public class PaymentService {
public void pay(String type, BigDecimal amount) {
if ("alipay".equals(type)) {
// 直接实现
} else if ("wechat".equals(type)) {
// 直接实现
}
}
}
// 演进为策略模式
public interface PaymentStrategy {
void pay(BigDecimal amount);
}
public class PaymentService {
private PaymentStrategy strategy;
public void setStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void pay(BigDecimal amount) {
strategy.pay(amount);
}
}
// 在以下情况考虑引入设计模式:
if (changeFrequency > THRESHOLD ||
conditionalComplexity > ACCEPTABLE ||
classResponsibility > SINGLE) {
considerDesignPattern();
}
问题背景:微服务架构下传统设计模式如何适应分布式环境?
解决方案:
// 代理模式在API网关中的实现
@RestController
@RequestMapping("/api/product")
public class ProductApiGateway {
@Autowired
private ProductServiceClient client;
@GetMapping("/{id}")
public Product getProduct(@PathVariable String id) {
// 可添加缓存、熔断等逻辑
return client.getProduct(id);
}
}
// 观察者模式的分布式实现
@EventListener
public void handleOrderCreated(OrderCreatedEvent event) {
// 库存服务处理
inventoryService.reduceStock(event.getProductId(), event.getQuantity());
// 发券服务处理
couponService.issueCoupon(event.getUserId());
}
问题背景:在DDD架构中如何合理运用设计模式?
解决方案:
public class OrderFactory {
public Order createOrder(List<OrderItem> items, Customer customer) {
Order order = new Order(customer);
items.forEach(order::addItem);
order.validate();
return order;
}
}
public interface OrderRepository {
Order findById(OrderId id);
void save(Order order);
}
public interface PricingStrategy {
Money calculatePrice(Order order);
}
public class VIPPricingStrategy implements PricingStrategy {
@Override
public Money calculatePrice(Order order) {
return order.getTotal().multiply(0.9);
}
}
public interface Specification<T> {
boolean isSatisfiedBy(T candidate);
Specification<T> and(Specification<T> other);
}
public class OrderSpecification implements Specification<Order> {
// 实现细节
}
public class Order {
private List<DomainEvent> domainEvents = new ArrayList<>();
public void cancel() {
this.status = OrderStatus.CANCELLED;
domainEvents.add(new OrderCancelledEvent(this.id));
}
public List<DomainEvent> getDomainEvents() {
return Collections.unmodifiableList(domainEvents);
}
}
缓存代理模式:
public class CachedUserRepository implements UserRepository {
private final UserRepository delegate;
private final Cache cache;
@Override
public User findById(String id) {
User user = cache.get(id);
if (user == null) {
user = delegate.findById(id);
cache.put(id, user);
}
return user;
}
}
异步观察者模式:
public class AsyncEventBus {
private final Executor executor;
private final Map<Class<?>, List<Consumer<?>>> handlers = new ConcurrentHashMap<>();
public <E> void registerHandler(Class<E> eventType, Consumer<E> handler) {
handlers.computeIfAbsent(eventType, k -> new CopyOnWriteArrayList<>())
.add(handler);
}
public <E> void publish(E event) {
List<Consumer<?>> consumers = handlers.get(event.getClass());
if (consumers != null) {
consumers.forEach(consumer -> {
executor.execute(() -> {
@SuppressWarnings("unchecked")
Consumer<E> handler = (Consumer<E>) consumer;
handler.accept(event);
});
});
}
}
}
RPC框架中的代理模式:
public class RpcProxy implements InvocationHandler {
private final Class<?> serviceInterface;
public static <T> T create(Class<T> interfaceClass) {
return (T) Proxy.newProxyInstance(
interfaceClass.getClassLoader(),
new Class<?>[] {interfaceClass},
new RpcProxy(interfaceClass));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
// 构造RPC请求并发送
return sendRpcRequest(method, args);
}
}
消息队列的建造者模式:
Message message = new MessageBuilder()
.withTopic("order_created")
.withKey(orderId)
.withBody(order)
.withDelay(5, TimeUnit.MINUTES)
.build();
producer.send(message);
设计模式在大型互联网企业的应用呈现以下趋势:
阿里/字节工程师的建议:
设计模式作为软件设计的经验总结,随着技术发展不断演进。工程师应当深入理解其核心思想,灵活运用于实际场景,而非机械套用。在未来技术变革中,设计模式仍将是构建高质量软件系统的重要工具。