今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

标签:#patterns

找到 7 篇相关文章

开发者

Making ServiceLoader usable: a provider factory

I keep coming back to java.util.ServiceLoader . I have used it to put a JSON layer behind a contract, so the core code carries no direct dependency on any particular JSON library and I can swap the implementation without touching callers. The same shape works for JWT handling, where the concrete library might be jose4j or another JOSE implementation, and you can easily find other decoupling use-cases. The motivation is always the same: the application should depend on a capability, not on a vendor. A while back I wrote about exactly that idea in Rediscovering Java ServiceLoader: Beyond Plugins and Into Capabilities , where the argument was to treat ServiceLoader as capability discovery rather than a plugin system. That piece hit the limitation everyone hits — the no-argument constructor — and worked around it with a default constructor plus a dynamic proxy that built the real object through a factory on each call. It works, but it is indirection bolted on after the fact, not a design. This post is the part I never pinned down back then: turning that workaround into a small, explicit pattern. The running example below is a mock payments system, with Stripe and PayPal specializations, because it is compact enough to show end to end. The JSON and JWT cases cited can be built with the same structure. The two limits ServiceLoader leaves you The first is the no-argument constructor. Whatever ServiceLoader instantiates must have a public, parameterless constructor. My StripePaymentService takes an API key, so it cannot be the class ServiceLoader loads — not unless I bolt on some init-after-construction step, which I would rather avoid. The second is selection, or rather the lack of it. ServiceLoader gives you every implementation it finds, in roughly classpath order. There is no id, nothing to prioritise on, and no way to ask whether a given one even applies in the current environment. With two backends on the classpath and only one configured, working out which to use is

2026-07-14 原文 →
AI 资讯

End-to-end Design Walkthrough — Full System Design

Full system design walkthrough: vì sao quy trình 5 bước quan trọng hơn thuật ngữ, và cái bẫy nhảy thẳng vào deep-dive Một buổi phỏng vấn system design 45–60 phút không đánh giá xem thí sinh biết bao nhiêu tên công nghệ, mà đánh giá xem thí sinh có xử lý được một bài toán mơ hồ theo một quy trình có kỷ luật hay không. Cùng đề "thiết kế URL shortener", người thất bại thường bắt đầu bằng "dùng Cassandra vì scale tốt" ngay ở phút thứ hai — chưa hỏi scale bao nhiêu, chưa biết read/write ratio, chưa đồng ý interface. Người pass đi theo một trình tự cứng: requirements → estimation → high-level → deep-dive → tradeoff . Cùng một đề, cùng thời lượng, nhưng người thứ hai dẫn dắt được interviewer thay vì bị dí. Bài này mô tả quy trình đó ở mức thực dụng, các thất bại thường gặp khi bỏ bước, và một hands-on end-to-end trên URL shortener để tự luyện. Cơ chế hoạt động Quy trình chuẩn được nhiều tài liệu tổng hợp (Alex Xu — System Design Interview vol.1; Donne Martin — system-design-primer ; Kleppmann — Designing Data-Intensive Applications ) đều có 4–5 bước gần như trùng nhau. Đây là khung 5 bước dùng thực tế trong phỏng vấn: Requirements clarification (~5 phút). Chốt functional requirement (hệ thống làm gì — API nào, use case nào) và non-functional requirement (availability target, latency target, consistency yêu cầu, security, cost). Không đoán — hỏi lại interviewer. Output: 3–5 gạch đầu dòng functional + 3–5 gạch NFR + danh sách "out of scope" (analytics, billing, ...). Back-of-the-envelope estimation (~5 phút). Tính DAU, QPS peak/avg, read:write ratio, storage growth theo năm, bandwidth. Không cần chính xác — cần đúng order of magnitude để quyết định "cần shard hay không", "cache có ý nghĩa không", "một node đủ hay phải scale ngang". High-level design (~10–15 phút). Vẽ box diagram: client → LB → app tier → cache → primary datastore → async worker → object storage/CDN. Định nghĩa API (endpoint, request/response, status code) và data model (schema chính, index chính). Ở bước này

2026-07-08 原文 →
AI 资讯

Service Communication Patterns in .NET Core and Azure

This article is part of the Comprehensive Guide to Microservices Architecture in .NET Core, Cloud and Azure series. Asynchronous Messaging with Azure Service Bus Azure Service Bus provides enterprise-grade messaging infrastructure with advanced features for reliable message delivery, ordering guarantees, and complex routing scenarios. Service Bus vs Azure Queue Storage Azure Service Bus offers enterprise messaging capabilities including: Topics and subscriptions for pub/sub patterns Message sessions for ordered processing Transaction support across operations Dead-letter queues for failed messages Messages up to 100MB (premium tier) Advanced routing with filters and actions Azure Queue Storage provides: Simple FIFO queue operations Lower cost for basic scenarios Messages up to 64KB Best for simple point-to-point messaging When to Choose Service Bus Use Azure Service Bus when you need: Publish-subscribe patterns with multiple subscribers Guaranteed message ordering with sessions Transactional message processing Message size beyond 64KB Advanced routing and filtering Integration with hybrid or on-premises systems Implementation with .NET 9 .NET 9 introduces improved performance and simplified APIs for working with Azure Service Bus: // Producer using .NET 9 with improved performance public class OrderCreatedPublisher { private readonly ServiceBusSender _sender ; public OrderCreatedPublisher ( ServiceBusClient client ) { _sender = client . CreateSender ( "order-events" ); } public async Task PublishOrderCreatedAsync ( Order order , CancellationToken cancellationToken = default ) { var message = new ServiceBusMessage ( JsonSerializer . Serialize ( order )) { MessageId = order . OrderId . ToString (), Subject = "OrderCreated" , ContentType = "application/json" , // .NET 9: Better support for distributed tracing ApplicationProperties = { [ "CorrelationId" ] = Activity . Current ?. Id ?? Guid . NewGuid (). ToString (), [ "OrderDate" ] = order . CreatedAt . ToString ( "O" )

2026-06-26 原文 →
AI 资讯

API Gateway Patterns in .NET Core and Azure

This article is part of the Comprehensive Guide to Microservices Architecture in .NET Core, Cloud and Azure series. API gateways serve as the entry point for client applications in distributed architectures, handling request routing, composition, and protocol translation. As systems grow more complex with multiple client types and backend services, choosing the right gateway pattern becomes crucial for maintaining performance, scalability, and developer productivity. This article explores two powerful API gateway patterns in .NET: the Backend for Frontend (BFF) pattern, which creates client-specific gateways, and GraphQL, which offers flexible, query-driven data fetching. Both patterns address the challenge of efficiently serving diverse clients while maintaining clean architecture and optimal performance. Backend for Frontend (BFF) Pattern Web BFF Implementation The web BFF returns detailed, enriched data suitable for desktop browsers with higher bandwidth and processing power: [ ApiController ] [ Route ( "api/web/[controller]" )] public class OrdersController : ControllerBase { private readonly IOrderServiceClient _orderClient ; private readonly ICustomerServiceClient _customerClient ; private readonly IInventoryServiceClient _inventoryClient ; [ HttpGet ( "{id}" )] public async Task < WebOrderDto > GetOrder ( Guid id ) { // Execute parallel calls to improve response time var orderTask = _orderClient . GetOrderAsync ( id ); var customerTask = _customerClient . GetCustomerAsync ( id ); var inventoryTask = _inventoryClient . GetInventoryStatusAsync ( id ); await Task . WhenAll ( orderTask , customerTask , inventoryTask ); return new WebOrderDto { Order = orderTask . Result , Customer = customerTask . Result , InventoryStatus = inventoryTask . Result , // Include additional rich data for enhanced web UI experience RecommendedProducts = await GetRecommendationsAsync ( id ) }; } } Mobile BFF Implementation The mobile BFF provides optimized, lightweight responses to min

2026-06-26 原文 →
AI 资讯

Enterprise Design Patterns in Python: Repository & Unit of Work — Real-World E-Commerce Example

Enterprise Design Patterns in Python: Repository & Unit of Work 🐍🏗️ Series: Enterprise Application Architecture | Source: Fowler's EAA Catalog | Code: GitHub Repository 🧠 What Are Enterprise Design Patterns? Martin Fowler's Patterns of Enterprise Application Architecture (2002) is one of the most influential books in software engineering. It documents recurring architectural solutions — patterns — that solve common problems in enterprise systems: how to organize domain logic, how to talk to databases, how to handle transactions, and more. In this article, we'll explore two of the most powerful and widely-used patterns from that catalog: Pattern Category Core Purpose Repository Data Source Abstracts data access behind a collection-like interface Unit of Work Data Source Tracks object changes and commits them as a single transaction These two patterns work beautifully together — and you'll see exactly why with a real-world example. 🛒 The Problem: An E-Commerce Order System Imagine you're building a backend for an online store. When a customer places an order: A new Order is created Each Product 's stock is decremented A Payment record is registered If any of these steps fail midway, the entire operation should roll back — no partial state. This is exactly the problem the Unit of Work pattern solves, and the Repository pattern makes it all cleanly testable. 📁 Repository Pattern Definition "A Repository mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." — Martin Fowler, PoEAA The Repository acts as an in-memory collection of domain objects. Your business logic never knows if it's talking to PostgreSQL, SQLite, or even a mock list — it just calls .add() , .get() , .list() . Domain Model # models.py from dataclasses import dataclass , field from typing import List from uuid import uuid4 @dataclass class Product : id : str name : str price : float stock : int @dataclass class OrderItem : product_id : str qua

2026-06-20 原文 →
AI 资讯

What Happens When an AI Agent Manages Your Password Vault

TL;DR Claude Code and the op CLI reorganized 690 credentials — four vaults, 390 items tagged, SSH agent configured — in one session. This is AI-native work: the agent operated the vault; the human set direction and approved via Touch ID. The CLI failed on 18 items with social-auth ( UNKNOWN field type) — hard failure, not graceful degradation; a real reliability blocker for team-scale use. The bug was filed from the terminal via the GitHub CLI in the same session it was found. If your password manager has a CLI, you already have everything needed to run this. I've been a 1Password user for years. Not in a conscious, intentional way — more in the way you use a good chair: it became part of how I work and I stopped thinking about it. That changed when I set up a new machine. I had to install 1Password, wire up the SSH agent, reconnect the CLI, re-authenticate everything. The process took longer than it should have because I'd never written down what I'd built. I'd only accumulated it. And somewhere in the middle of that setup, it hit me: I had 690 credentials in one flat vault — logins from jobs I'd left years ago sitting next to active API keys, personal bank accounts mixed with infrastructure credentials, demo user passwords alongside production secrets. The kind of accumulation that happens when a tool works well enough that you never stop to organize it. I'd been meaning to clean it up for a long time. I never did, because the job is exactly the kind of work that's too tedious to do manually and too important to skip: touch every item, make a judgment call, move it somewhere sensible, repeat 690 times. Then I realized: with Claude Code and the op CLI, this was now actually possible. Not assisted — the agent could do it. So I handed it the keys. What "AI-native" actually means here Quick context on timing: 1Password launched its SSH agent and CLI 2.0 in March 2022. Git commit signing via the vault came six months later. These are mature, stable features — not betas

2026-06-06 原文 →