1Minh chọn FREESHIP; client tạo new ApplyVoucherCommand(cart, "FREESHIP"). Yêu cầu giờ là một đối tượng giữ receiver Cart và tham số code, có thể sống lâu hơn lời gọi.Minh selects FREESHIP; the client creates new ApplyVoucherCommand(cart, "FREESHIP"). The request is now an object holding the Cart receiver and the code argument, able to outlive the call.
2Client gọi history.run(cmd). CartHistory gọi cmd.execute() qua interface Command, nên không cần biết cách áp voucher.The client calls history.run(cmd). CartHistory calls cmd.execute() through the Command interface, so it needs no voucher logic.
3execute() lưu previous = cart.voucher() (đang là LUNCH10) rồi gọi cart.applyVoucher("FREESHIP"). Cart mới là nơi xử lý nghiệp vụ.execute() saves previous = cart.voucher() (currently LUNCH10), then calls cart.applyVoucher("FREESHIP"). Cart owns the business logic.
4execute() xong thì run() mới done.push(cmd), xóa stack undone (thao tác mới làm mất redo) và ghi log bằng cmd.label().Only after execute() returns does run() call done.push(cmd), clear the undone stack (a new action invalidates redo) and log with cmd.label().
5Minh bấm Hoàn tác: history.undo() lấy done.peek() — command mới nhất — và gọi cmd.undo(). Command gọi cart.applyVoucher(previous) để trả về LUNCH10; sau đó lịch sử chuyển nó sang stack undone.Minh presses Undo: history.undo() takes done.peek() — the latest command — and calls cmd.undo(). The command calls cart.applyVoucher(previous) to restore LUNCH10; history then moves it to the undone stack.
6Đổi ý, Minh bấm Làm lại: redo() lấy undone.peek(), gọi lại execute() — previous được đọc lại là LUNCH10 và voucher thành FREESHIP — rồi đẩy command về done.Changing her mind, Minh presses Redo: redo() takes undone.peek(), calls execute() again — previous is re-read as LUNCH10 and the voucher becomes FREESHIP — then pushes the command back onto done.
7Bản Go: History.Run(ctx, &ApplyVoucher{Cart, Code}) gọi Execute(ctx) và chỉ append vào done khi không có lỗi; lỗi được bọc kèm kiểu command. History.Undo gọi Undo(ctx) của phần tử cuối, gán nil rồi cắt slice.In Go: History.Run(ctx, &ApplyVoucher{Cart, Code}) calls Execute(ctx) and appends to done only on success; errors are wrapped with the command type. History.Undo calls Undo(ctx) on the last element, sets it to nil and shrinks the slice.
8Biến thể nhẹ nhất trong queue.go: Job chỉ là func(ctx) error. Một closure Job được gửi vào channel jobs; goroutine RunQueue nhận job, ok := <-jobs.The lightest variant in queue.go: Job is just func(ctx) error. A Job closure is sent into the jobs channel; the RunQueue goroutine receives job, ok := <-jobs.
9RunQueue gọi job(ctx) lần lượt từng việc; nếu lỗi thì ghi log rồi chạy việc tiếp theo. Khi ctx.Done() hoặc channel đóng, goroutine thoát.RunQueue calls job(ctx) one job at a time; on error it logs and moves on. When ctx.Done() fires or the channel closes, the goroutine exits.