You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中实现带优先级的执行与撤销方法?(快递配送场景)

Hey Juan, great question! Let’s walk through how to build that execute/undo logic for your delivery service using priority queues and stacks—this is a perfect scenario for combining these two data structures to track state changes smoothly.

Core Concept Breakdown

First, let’s align on why these structures fit your needs:

  • Priority Queue: Manages your pending packages so you always handle the highest-priority deliveries first (e.g., urgent express orders, time-sensitive shipments).
  • Stack: Tracks every delivery operation in reverse order (LIFO), which is ideal for undo functionality—you’ll always revert the most recent action first.
Step-by-Step Implementation

Let’s use Python for concrete examples, but the logic translates to any language with priority queue/stack support.

1. Define Package State & Data Structures

First, create a way to represent packages and their statuses:

from enum import Enum
import heapq

# Define possible package statuses
class PackageStatus(Enum):
    PENDING = "pending"
    DELIVERED = "delivered"

# Package class with priority support
class Package:
    def __init__(self, package_id, priority, status=PackageStatus.PENDING):
        self.package_id = package_id
        self.priority = priority  # Higher number = higher priority (adjust as needed)
        self.status = status

    # Required for priority queue (heapq in Python uses __lt__ for sorting)
    def __lt__(self, other):
        return self.priority > other.priority  # Push higher priority to the front

2. Build the Delivery Service Class

This class will wrap the priority queue, stack, and core logic:

class DeliveryService:
    def __init__(self):
        self.pending_queue = []  # Priority queue (heap) for pending packages
        self.delivered_cache = {}  # Quick lookup for delivered packages
        self.undo_stack = []  # Tracks operations for undo

    # Add a new package to the pending queue
    def add_package(self, package):
        heapq.heappush(self.pending_queue, package)
        print(f"Added package {package.package_id} to pending queue (priority: {package.priority})")

    # Execute a delivery (highest priority first)
    def execute_delivery(self):
        if not self.pending_queue:
            print("No pending packages to deliver!")
            return None
        
        # Pop highest priority package from queue
        package = heapq.heappop(self.pending_queue)
        old_status = package.status
        
        # Update package state to delivered
        package.status = PackageStatus.DELIVERED
        self.delivered_cache[package.package_id] = package

        # Record the operation for undo: (operation_type, package_id, old_status)
        self.undo_stack.append(("DELIVER", package.package_id, old_status))
        print(f"Delivered package {package.package_id}")
        return package

    # Undo the most recent delivery
    def undo_delivery(self):
        if not self.undo_stack:
            print("No operations available to undo!")
            return None
        
        # Pop the latest operation from the stack
        op_type, package_id, old_status = self.undo_stack.pop()

        # Only handle delivery operations (extendable for other actions later)
        if op_type != "DELIVER":
            print(f"Cannot undo unsupported operation: {op_type}")
            return None
        
        # Retrieve the package from delivered cache
        package = self.delivered_cache.pop(package_id, None)
        if not package:
            print(f"Error: Package {package_id} not found in delivered records")
            return None
        
        # Restore old status and push back to pending queue
        package.status = old_status
        heapq.heappush(self.pending_queue, package)
        print(f"Undone delivery for package {package_id}")
        return package

3. Test the Logic

Here’s how you’d use the service:

# Initialize service
service = DeliveryService()

# Add test packages
service.add_package(Package("PKG-101", 3))
service.add_package(Package("PKG-102", 5))  # Higher priority
service.add_package(Package("PKG-103", 2))

# Execute deliveries
service.execute_delivery()  # Delivers PKG-102 first
service.execute_delivery()  # Delivers PKG-101

# Undo the last delivery
service.undo_delivery()  # Puts PKG-101 back to pending

# Check pending queue (should have PKG-101 and PKG-103)
print("\nCurrent pending packages:")
for pkg in service.pending_queue:
    print(f"- {pkg.package_id} (priority: {pkg.priority}, status: {pkg.status.value})")
Key Considerations for Your Project
  • Priority Customization: Adjust the __lt__ method in the Package class to match your business rules (e.g., sort by delivery deadline instead of numeric priority).
  • Operation Extensibility: If you add other actions (like canceling a pending package), extend the stack to track those operations too—just add new operation types and corresponding undo logic.
  • Thread Safety: If your service runs in a multi-threaded environment, add locks around queue/stack operations to prevent race conditions.
  • Persistence: For production, you might want to persist the undo stack and package state to a database, so operations survive restarts.

内容的提问来源于stack exchange,提问作者Juan Montoya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:14:57