惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
U
Unit 42
IT之家
IT之家
Y
Y Combinator Blog
T
Tailwind CSS Blog
B
Blog
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
Jina AI
Jina AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
J
Java Code Geeks
F
Fortinet All Blogs
T
The Blog of Author Tim Ferriss
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
H
Hackread – Cybersecurity News, Data Breaches, AI and More
人人都是产品经理
人人都是产品经理
腾讯CDC
Hugging Face - Blog
Hugging Face - Blog
GbyAI
GbyAI
博客园 - 司徒正美
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
L
LangChain Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
LLD:15-Order Management System
NOOB · 2026-06-27 · via DEV Community

NOOB

Order Management System - State Pattern Implementation

This is an implementation of the State design pattern for an e-commerce Order Management System. By utilizing this pattern, an order dictates its own lifecycle (Created, Paid, Shipped, Delivered) and strictly enforces business rules without relying on messy if/else or switch statements evaluating an "order status" flag.

Problem Statement

Building the backend flow for an e-commerce order that transitions through four sequential states: Created, Paid, Shipped, and Delivered. The challenge is ensuring that illegal operations—like attempting to ship an unpaid order or paying for an order that has already been delivered—are gracefully blocked based on the current state.

Key Challenge:

  • If ship() is called in the Created state → "ERROR: Cannot ship an unpaid order."
  • The happy path must flow perfectly: Created -> pay() -> Paid -> ship() -> Shipped -> deliver() -> Delivered.
  • The Context (Order) should not contain the validation logic; the states themselves must handle their own localized rules and transitions.

Class Diagram

                            +----------------------+
                            |    OrderManagement   | <-------------------+
                            +----------------------+                     |
                            | - currentState       |                     |
                            +----------------------+                     |
                            | + setState()         |                     |
                            | + pay()              |                     |
                            | + ship()             |                     |
                            | + deliver()          |                     |
                            +----------+-----------+                     |
                                       |                                 |
                                       | (Delegates to)                  |
                                       v                                 |
                            +----------------------+                     |
                            |        State         |                     |
                            |      (Interface)     |                     |
                            +----------------------+                     |
                            | + pay()              |                     |
                            | + ship()             |                     |
                            | + deliver()          |                     |
                            +----------+-----------+                     |
                                       ^                                 |
                                       | (Implements)                    |
            +--------------------------+--------------------------+      |
            |                          |                          |      |
 +----------+----------+    +----------+----------+    +----------+------+-+
 |    CreatedState     |    |      PaidState      |    |   ShippedState    |
 +---------------------+    +---------------------+    +-------------------+
 | - orderManagement   |--->| - orderManagement   |--->| - orderManagement |
 | + pay()             |    | + pay()             |    | + pay()           |
 | + ship()            |    | + ship()            |    | + ship()          |
 | + deliver()         |    | + deliver()         |    | + deliver()       |
 +---------------------+    +---------------------+    +-------------------+
              (And DeliveredState follows the exact same pattern!)

Implementation

package state.orderManagementSystem;

public class OrderManagementSystem {

    /**
     * 1. The State Interface
     * Defines the core actions that can be performed on an order.
     */
    interface State {
        void pay();
        void ship();
        void deliver();
    }

    /**
     * 2. The Context (OrderManagement)
     * Maintains a reference to the current state and delegates actions.
     */
    static class OrderManagement {
        State createdState;
        State paidState;
        State shippedState;
        State deliveredState;

        State currentState;

        public OrderManagement() {
            // Pass 'this' so states can talk back to the Context to change states
            createdState = new CreatedState(this);
            paidState = new PaidState(this);
            shippedState = new ShippedState(this);
            deliveredState = new DeliveredState(this);

            // Order starts in the Created state
            currentState = createdState;
        }

        public void setState(State state) {
            this.currentState = state;
        }

        public void pay() {
            currentState.pay();
        }

        public void ship() {
            currentState.ship();
        }

        public void deliver() {
            currentState.deliver();
        }
    }

    /**
     * 3. Concrete State: Created
     * Order is placed, waiting for payment.
     */
    static class CreatedState implements State {
        private final OrderManagement orderManagement;

        public CreatedState(OrderManagement orderManagement) {
            this.orderManagement = orderManagement;
        }

        @Override
        public void pay() {
            System.out.println("Payment successful! Order is now Paid.");
            orderManagement.setState(orderManagement.paidState); // Transition
        }

        @Override
        public void ship() {
            System.out.println("ERROR: Cannot ship an unpaid order.");
        }

        @Override
        public void deliver() {
            System.out.println("ERROR: Cannot deliver an unpaid order.");
        }
    }

    /**
     * 3. Concrete State: Paid
     * Payment is successful, waiting for dispatch.
     */
    static class PaidState implements State {
        private final OrderManagement orderManagement;

        public PaidState(OrderManagement orderManagement) {
            this.orderManagement = orderManagement;
        }

        @Override
        public void pay() {
            System.out.println("ERROR: Order is already paid.");
        }

        @Override
        public void ship() {
            System.out.println("Order dispatched! Order is now Shipped.");
            orderManagement.setState(orderManagement.shippedState); // Transition
        }

        @Override
        public void deliver() {
            System.out.println("ERROR: Cannot deliver an order that hasn't shipped.");
        }
    }

    /**
     * 3. Concrete State: Shipped
     * The order is on the truck, waiting for delivery.
     */
    static class ShippedState implements State {
        private final OrderManagement orderManagement;

        public ShippedState(OrderManagement orderManagement) {
            this.orderManagement = orderManagement;
        }

        @Override
        public void pay() {
            System.out.println("ERROR: Order is already paid.");
        }

        @Override
        public void ship() {
            System.out.println("ERROR: Order is already shipped.");
        }

        @Override
        public void deliver() {
            System.out.println("Order dropped off! Order is now Delivered.");
            orderManagement.setState(orderManagement.deliveredState); // Transition
        }
    }

    /**
     * 3. Concrete State: Delivered
     * The order is complete. No further actions allowed.
     */
    static class DeliveredState implements State {
        private final OrderManagement orderManagement;

        public DeliveredState(OrderManagement orderManagement) {
            this.orderManagement = orderManagement;
        }

        @Override
        public void pay() {
            System.out.println("ERROR: Order is already complete.");
        }

        @Override
        public void ship() {
            System.out.println("ERROR: Order is already complete.");
        }

        @Override
        public void deliver() {
            System.out.println("ERROR: Order is already delivered.");
        }
    }

    /**
     * 4. Main Driver
     */
    public static void main(String[] args) {
        System.out.println("---- Order Management System ----");

        OrderManagement order = new OrderManagement();

        System.out.println("\n--- Attempt 1: Trying to ship before paying ---");
        order.ship();

        System.out.println("\n--- Attempt 2: Happy Path ---");
        order.pay();
        order.ship();
        order.deliver();

        System.out.println("\n--- Attempt 3: Action after completion ---");
        order.pay();
    }
}

Key Features

  • Strict Business Logic Pipeline: The pattern perfectly models a one-way sequential pipeline (Created -> Paid -> Shipped -> Delivered) where skipping steps is inherently impossible.
  • Localized Error Handling: Instead of the Context checking if (status == CREATED), the CreatedState naturally knows how to reject ship() and deliver() requests.
  • No Complex Conditionals: Adding a new step (e.g., RefundedState) requires creating a new class rather than modifying massive switch blocks in the core OrderManagement logic.
  • Self-Contained Transitions: Each state is responsible for handing the baton to the next logical state via orderManagement.setState().

How It Works

  1. Initialization: When OrderManagement is instantiated, it initializes all possible states and defaults its currentState to CreatedState.
  2. Invalid Action: If the client calls ship() while in CreatedState, the request is passed to CreatedState.ship(), which outputs an error and prevents any transition.
  3. Happy Path Transition: Calling pay() on CreatedState executes the payment logic and transitions the context to PaidState. Subsequent calls to ship() and deliver() cascade through the remaining states.
  4. Terminal State: Once it reaches DeliveredState, all core actions (pay, ship, deliver) act as dead ends, preventing further manipulation of a completed order.

Sample Output

---- Order Management System ----

--- Attempt 1: Trying to ship before paying ---
ERROR: Cannot ship an unpaid order.

--- Attempt 2: Happy Path ---
Payment successful! Order is now Paid.
Order dispatched! Order is now Shipped.
Order dropped off! Order is now Delivered.

--- Attempt 3: Action after completion ---
ERROR: Order is already complete.