{"id":10021267,"date":"2026-02-21T21:22:54","date_gmt":"2026-02-21T13:22:54","guid":{"rendered":"https:\/\/itmax.cn\/?p=10021267"},"modified":"2026-02-21T21:22:54","modified_gmt":"2026-02-21T13:22:54","slug":"python%e4%bb%a3%e7%a0%81%e9%87%8d%e6%9e%84%e6%8a%80%e5%b7%a7%e4%b8%8e%e5%9d%8f%e5%91%b3%e9%81%93%e8%af%86%e5%88%ab","status":"publish","type":"post","link":"https:\/\/itmax.cn\/?p=10021267","title":{"rendered":"Python\u4ee3\u7801\u91cd\u6784\u6280\u5de7\u4e0e\u574f\u5473\u9053\u8bc6\u522b"},"content":{"rendered":"<h2>Python\u4ee3\u7801\u91cd\u6784\u6280\u5de7\u4e0e\u574f\u5473\u9053\u8bc6\u522b<\/h2>\n<p>\u4ee3\u7801\u91cd\u6784\u662f\u6539\u5584\u4ee3\u7801\u7ed3\u6784\u800c\u4e0d\u6539\u53d8\u5916\u90e8\u884c\u4e3a\u7684\u8fc7\u7a0b\u3002\u672c\u6587\u5c06\u4ecb\u7ecdPython\u4ee3\u7801\u91cd\u6784\u6280\u5de7\u548c\u574f\u5473\u9053\u8bc6\u522b\u3002<\/p>\n<h3>\u4ee3\u7801\u574f\u5473\u9053<\/h3>\n<ul>\n<li><strong>\u957f\u65b9\u6cd5<\/strong>\uff1a\u65b9\u6cd5\u8fc7\u957f\uff0c\u804c\u8d23\u8fc7\u591a<\/li>\n<li><strong>\u91cd\u590d\u4ee3\u7801<\/strong>\uff1a\u76f8\u540c\u6216\u76f8\u4f3c\u7684\u4ee3\u7801\u591a\u5904\u51fa\u73b0<\/li>\n<li><strong>\u8fc7\u5927\u7684\u7c7b<\/strong>\uff1a\u7c7b\u5305\u542b\u8fc7\u591a\u5c5e\u6027\u548c\u65b9\u6cd5<\/li>\n<li><strong>\u8fc7\u957f\u53c2\u6570\u5217\u8868<\/strong>\uff1a\u65b9\u6cd5\u53c2\u6570\u8fc7\u591a<\/li>\n<\/ul>\n<h3>\u91cd\u6784\u6838\u5fc3\u5b9e\u73b0<\/h3>\n<pre><code class=\"python\">&quot;&quot;&quot;\nPython\u4ee3\u7801\u91cd\u6784\u6280\u5de7\u4e0e\u574f\u5473\u9053\u8bc6\u522b\n\u5305\u542b\u63d0\u53d6\u65b9\u6cd5\u3001\u5185\u8054\u3001\u79fb\u52a8\u65b9\u6cd5\u7b49\u91cd\u6784\u6280\u5de7\n&quot;&quot;&quot;\n\nfrom typing import List, Dict, Optional, Tuple\nfrom dataclasses import dataclass\nfrom enum import Enum\n\n\n# ============ \u574f\u5473\u9053\u793a\u4f8b ============\nclass OrderProcessorBad:\n    &quot;&quot;&quot;\u574f\u5473\u9053\u793a\u4f8b\uff1a\u8fc7\u5927\u7684\u7c7b&quot;&quot;&quot;\n    \n    def __init__(self):\n        self.orders = []\n        self.customers = []\n        self.products = []\n        self.inventory = {}\n        self.shipping_rates = {}\n    \n    def process_order(self, order_id: int, customer_id: int, \n                     product_ids: List[int], quantities: List[int],\n                     shipping_address: str, payment_method: str,\n                     discount_code: Optional[str] = None,\n                     gift_wrap: bool = False,\n                     special_instructions: str = &quot;&quot;):\n        &quot;&quot;&quot;\u574f\u5473\u9053\uff1a\u8fc7\u957f\u53c2\u6570\u5217\u8868&quot;&quot;&quot;\n        # \u9a8c\u8bc1\u5ba2\u6237\n        customer = None\n        for c in self.customers:\n            if c['id'] == customer_id:\n                customer = c\n                break\n        \n        if not customer:\n            raise ValueError(&quot;\u5ba2\u6237\u4e0d\u5b58\u5728&quot;)\n        \n        # \u9a8c\u8bc1\u4ea7\u54c1\n        products = []\n        for pid in product_ids:\n            for p in self.products:\n                if p['id'] == pid:\n                    products.append(p)\n                    break\n        \n        # \u8ba1\u7b97\u4ef7\u683c\n        total = 0\n        for i, product in enumerate(products):\n            qty = quantities[i]\n            price = product['price']\n            \n            # \u5e94\u7528\u6298\u6263\n            if discount_code:\n                if discount_code == &quot;SAVE10&quot;:\n                    price = price * 0.9\n                elif discount_code == &quot;SAVE20&quot;:\n                    price = price * 0.8\n            \n            total += price * qty\n        \n        # \u8ba1\u7b97\u8fd0\u8d39\n        if total &lt; 50:\n            shipping = 5.99\n        elif total &lt; 100:\n            shipping = 2.99\n        else:\n            shipping = 0\n        \n        total += shipping\n        \n        # \u5904\u7406\u652f\u4ed8\n        if payment_method == &quot;credit_card&quot;:\n            print(f&quot;\u5904\u7406\u4fe1\u7528\u5361\u652f\u4ed8: {total}&quot;)\n        elif payment_method == &quot;paypal&quot;:\n            print(f&quot;\u5904\u7406PayPal\u652f\u4ed8: {total}&quot;)\n        elif payment_method == &quot;bank_transfer&quot;:\n            print(f&quot;\u5904\u7406\u94f6\u884c\u8f6c\u8d26: {total}&quot;)\n        \n        # \u521b\u5efa\u8ba2\u5355\n        order = {\n            'id': order_id,\n            'customer': customer,\n            'products': products,\n            'total': total,\n            'shipping_address': shipping_address\n        }\n        \n        self.orders.append(order)\n        return order\n\n\n# ============ \u91cd\u6784\u540e\u4ee3\u7801 ============\n@dataclass\nclass Customer:\n    &quot;&quot;&quot;\u5ba2\u6237&quot;&quot;&quot;\n    id: int\n    name: str\n    email: str\n\n\n@dataclass\nclass Product:\n    &quot;&quot;&quot;\u4ea7\u54c1&quot;&quot;&quot;\n    id: int\n    name: str\n    price: float\n\n\n@dataclass\nclass OrderItem:\n    &quot;&quot;&quot;\u8ba2\u5355\u9879&quot;&quot;&quot;\n    product: Product\n    quantity: int\n    \n    @property\n    def subtotal(self) -&gt; float:\n        return self.product.price * self.quantity\n\n\nclass DiscountStrategy:\n    &quot;&quot;&quot;\u6298\u6263\u7b56\u7565&quot;&quot;&quot;\n    \n    DISCOUNTS = {\n        &quot;SAVE10&quot;: 0.9,\n        &quot;SAVE20&quot;: 0.8,\n        &quot;SAVE50&quot;: 0.5\n    }\n    \n    @classmethod\n    def apply_discount(cls, price: float, code: Optional[str]) -&gt; float:\n        if code and code in cls.DISCOUNTS:\n            return price * cls.DISCOUNTS[code]\n        return price\n\n\nclass ShippingCalculator:\n    &quot;&quot;&quot;\u8fd0\u8d39\u8ba1\u7b97\u5668&quot;&quot;&quot;\n    \n    @staticmethod\n    def calculate_shipping(order_total: float) -&gt; float:\n        if order_total &lt; 50:\n            return 5.99\n        elif order_total &lt; 100:\n            return 2.99\n        return 0\n\n\nclass PaymentProcessor:\n    &quot;&quot;&quot;\u652f\u4ed8\u5904\u7406\u5668&quot;&quot;&quot;\n    \n    def process_payment(self, amount: float, method: str) -&gt; bool:\n        processors = {\n            &quot;credit_card&quot;: self._process_credit_card,\n            &quot;paypal&quot;: self._process_paypal,\n            &quot;bank_transfer&quot;: self._process_bank_transfer\n        }\n        \n        processor = processors.get(method)\n        if processor:\n            return processor(amount)\n        raise ValueError(f&quot;\u4e0d\u652f\u6301\u7684\u652f\u4ed8\u65b9\u5f0f: {method}&quot;)\n    \n    def _process_credit_card(self, amount: float) -&gt; bool:\n        print(f&quot;\u5904\u7406\u4fe1\u7528\u5361\u652f\u4ed8: {amount}&quot;)\n        return True\n    \n    def _process_paypal(self, amount: float) -&gt; bool:\n        print(f&quot;\u5904\u7406PayPal\u652f\u4ed8: {amount}&quot;)\n        return True\n    \n    def _process_bank_transfer(self, amount: float) -&gt; bool:\n        print(f&quot;\u5904\u7406\u94f6\u884c\u8f6c\u8d26: {amount}&quot;)\n        return True\n\n\nclass CustomerRepository:\n    &quot;&quot;&quot;\u5ba2\u6237\u4ed3\u50a8&quot;&quot;&quot;\n    \n    def __init__(self):\n        self._customers: Dict[int, Customer] = {}\n    \n    def add(self, customer: Customer):\n        self._customers[customer.id] = customer\n    \n    def get_by_id(self, customer_id: int) -&gt; Optional[Customer]:\n        return self._customers.get(customer_id)\n\n\nclass ProductRepository:\n    &quot;&quot;&quot;\u4ea7\u54c1\u4ed3\u50a8&quot;&quot;&quot;\n    \n    def __init__(self):\n        self._products: Dict[int, Product] = {}\n    \n    def add(self, product: Product):\n        self._products[product.id] = product\n    \n    def get_by_ids(self, product_ids: List[int]) -&gt; List[Product]:\n        return [self._products[pid] for pid in product_ids if pid in self._products]\n\n\n@dataclass\nclass Order:\n    &quot;&quot;&quot;\u8ba2\u5355&quot;&quot;&quot;\n    id: int\n    customer: Customer\n    items: List[OrderItem]\n    shipping_address: str\n    payment_method: str\n    discount_code: Optional[str] = None\n    \n    @property\n    def subtotal(self) -&gt; float:\n        return sum(item.subtotal for item in self.items)\n    \n    @property\n    def shipping_cost(self) -&gt; float:\n        return ShippingCalculator.calculate_shipping(self.subtotal)\n    \n    @property\n    def total(self) -&gt; float:\n        discounted = sum(\n            DiscountStrategy.apply_discount(item.subtotal, self.discount_code)\n            for item in self.items\n        )\n        return discounted + self.shipping_cost\n\n\nclass OrderService:\n    &quot;&quot;&quot;\u8ba2\u5355\u670d\u52a1\uff08\u91cd\u6784\u540e\uff09&quot;&quot;&quot;\n    \n    def __init__(self):\n        self.customer_repo = CustomerRepository()\n        self.product_repo = ProductRepository()\n        self.payment_processor = PaymentProcessor()\n        self.orders: List[Order] = []\n    \n    def create_order(\n        self,\n        customer_id: int,\n        items_data: List[Tuple[int, int]],  # (product_id, quantity)\n        shipping_address: str,\n        payment_method: str,\n        discount_code: Optional[str] = None\n    ) -&gt; Order:\n        &quot;&quot;&quot;\u521b\u5efa\u8ba2\u5355&quot;&quot;&quot;\n        # \u83b7\u53d6\u5ba2\u6237\n        customer = self.customer_repo.get_by_id(customer_id)\n        if not customer:\n            raise ValueError(&quot;\u5ba2\u6237\u4e0d\u5b58\u5728&quot;)\n        \n        # \u83b7\u53d6\u4ea7\u54c1\u5e76\u521b\u5efa\u8ba2\u5355\u9879\n        product_ids = [item[0] for item in items_data]\n        products = self.product_repo.get_by_ids(product_ids)\n        \n        if len(products) != len(product_ids):\n            raise ValueError(&quot;\u90e8\u5206\u4ea7\u54c1\u4e0d\u5b58\u5728&quot;)\n        \n        order_items = [\n            OrderItem(product, qty)\n            for product, (_, qty) in zip(products, items_data)\n        ]\n        \n        # \u521b\u5efa\u8ba2\u5355\n        order = Order(\n            id=len(self.orders) + 1,\n            customer=customer,\n            items=order_items,\n            shipping_address=shipping_address,\n            payment_method=payment_method,\n            discount_code=discount_code\n        )\n        \n        # \u5904\u7406\u652f\u4ed8\n        self.payment_processor.process_payment(order.total, payment_method)\n        \n        self.orders.append(order)\n        return order\n\n\ndef demonstrate_refactoring():\n    &quot;&quot;&quot;\u6f14\u793a\u91cd\u6784&quot;&quot;&quot;\n    print(&quot;=&quot;*60)\n    print(&quot;\u4ee3\u7801\u91cd\u6784\u6f14\u793a&quot;)\n    print(&quot;=&quot;*60)\n    \n    # \u8bbe\u7f6e\u6570\u636e\n    service = OrderService()\n    \n    # \u6dfb\u52a0\u5ba2\u6237\n    service.customer_repo.add(Customer(1, &quot;Alice&quot;, &quot;alice@example.com&quot;))\n    \n    # \u6dfb\u52a0\u4ea7\u54c1\n    service.product_repo.add(Product(1, &quot;Laptop&quot;, 999.99))\n    service.product_repo.add(Product(2, &quot;Mouse&quot;, 29.99))\n    \n    # \u521b\u5efa\u8ba2\u5355\n    order = service.create_order(\n        customer_id=1,\n        items_data=[(1, 1), (2, 2)],\n        shipping_address=&quot;123 Main St&quot;,\n        payment_method=&quot;credit_card&quot;,\n        discount_code=&quot;SAVE10&quot;\n    )\n    \n    print(f&quot;\/n\u8ba2\u5355ID: {order.id}&quot;)\n    print(f&quot;\u5ba2\u6237: {order.customer.name}&quot;)\n    print(f&quot;\u5546\u54c1\u5c0f\u8ba1: ${order.subtotal:.2f}&quot;)\n    print(f&quot;\u8fd0\u8d39: ${order.shipping_cost:.2f}&quot;)\n    print(f&quot;\u603b\u8ba1: ${order.total:.2f}&quot;)\n    \n    print(&quot;\/n&quot; + &quot;=&quot;*60)\n    print(&quot;\u91cd\u6784\u6539\u8fdb&quot;)\n    print(&quot;=&quot;*60)\n    print(&quot;1. \u63d0\u53d6\u7c7b: Customer, Product, OrderItem&quot;)\n    print(&quot;2. \u63d0\u53d6\u65b9\u6cd5: ShippingCalculator, PaymentProcessor&quot;)\n    print(&quot;3. \u5f15\u5165\u7b56\u7565\u6a21\u5f0f: DiscountStrategy&quot;)\n    print(&quot;4. \u4f7f\u7528\u4ed3\u50a8\u6a21\u5f0f: CustomerRepository, ProductRepository&quot;)\n    print(&quot;5. \u51cf\u5c11\u53c2\u6570: \u4f7f\u7528\u5bf9\u8c61\u5c01\u88c5\u53c2\u6570&quot;)\n    print(&quot;=&quot;*60)\n\n\ndef main():\n    &quot;&quot;&quot;\u4e3b\u51fd\u6570&quot;&quot;&quot;\n    demonstrate_refactoring()\n\n\nif __name__ == &quot;__main__&quot;:\n    main()<\/code><\/pre>\n<h3>\u91cd\u6784\u67b6\u6784\u56fe<\/h3>\n<pre style=\"display:none;\"><code class=\"mermaid\">flowchart TB\n    subgraph Before[&quot;\u91cd\u6784\u524d&quot;]\n        B1[\u5927\u7c7b]\n        B2[\u957f\u65b9\u6cd5]\n        B3[\u91cd\u590d\u4ee3\u7801]\n    end\n    \n    subgraph After[&quot;\u91cd\u6784\u540e&quot;]\n        A1[\u5c0f\u7c7b]\n        A2[\u77ed\u65b9\u6cd5]\n        A3[\u7b56\u7565\u6a21\u5f0f]\n    end\n    \n    subgraph Techniques[&quot;\u91cd\u6784\u6280\u5de7&quot;]\n        T1[\u63d0\u53d6\u65b9\u6cd5]\n        T2[\u79fb\u52a8\u65b9\u6cd5]\n        T3[\u5f15\u5165\u53c2\u6570\u5bf9\u8c61]\n    end\n    \n    Before --&gt; Techniques --&gt; After<\/code><\/pre>\n<h3>\u5173\u952e\u8981\u70b9<\/h3>\n<ol>\n<li><strong>\u63d0\u53d6\u65b9\u6cd5<\/strong>\uff1a\u5c06\u957f\u65b9\u6cd5\u62c6\u5206\u4e3a\u5c0f\u65b9\u6cd5<\/li>\n<li><strong>\u79fb\u52a8\u65b9\u6cd5<\/strong>\uff1a\u5c06\u65b9\u6cd5\u653e\u5230\u5408\u9002\u7684\u7c7b\u4e2d<\/li>\n<li><strong>\u5f15\u5165\u53c2\u6570\u5bf9\u8c61<\/strong>\uff1a\u51cf\u5c11\u53c2\u6570\u6570\u91cf<\/li>\n<li><strong>\u7b56\u7565\u6a21\u5f0f<\/strong>\uff1a\u66ff\u6362\u6761\u4ef6\u8bed\u53e5<\/li>\n<li><strong>\u5355\u4e00\u804c\u8d23<\/strong>\uff1a\u6bcf\u4e2a\u7c7b\u53ea\u8d1f\u8d23\u4e00\u4ef6\u4e8b<\/li>\n<\/ol>\n<p>\u91cd\u6784\u662f\u6301\u7eed\u6539\u8fdb\u4ee3\u7801\u8d28\u91cf\u7684\u91cd\u8981\u5b9e\u8df5\u3002<\/p>\n<p><a href=\"https:\/\/segmentfault.com\/a\/1190000047615716\">https:\/\/segmentfault.com\/a\/1190000047615716<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python\u4ee3\u7801\u91cd\u6784\u6280\u5de7\u4e0e\u574f\u5473\u9053\u8bc6\u522b \u4ee3\u7801\u91cd\u6784\u662f\u6539\u5584\u4ee3\u7801\u7ed3\u6784\u800c\u4e0d\u6539\u53d8\u5916\u90e8\u884c\u4e3a\u7684\u8fc7\u7a0b\u3002\u672c\u6587\u5c06\u4ecb\u7ecdPython\u4ee3\u7801 [&hellip;]<\/p>\n","protected":false},"author":8,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[4],"tags":[],"class_list":["post-10021267","post","type-post","status-publish","format-standard","hentry","category-share"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10021267","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/users\/8"}],"replies":[{"embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10021267"}],"version-history":[{"count":0,"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10021267\/revisions"}],"wp:attachment":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10021267"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10021267"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10021267"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}