Skip to content

Instantly share code, notes, and snippets.

@reydx
Last active May 20, 2021 00:54
Show Gist options
  • Save reydx/3c0aa579b745e199aeb60402cc0ed71a to your computer and use it in GitHub Desktop.
Save reydx/3c0aa579b745e199aeb60402cc0ed71a to your computer and use it in GitHub Desktop.
design-pattern
# -*- coding: UTF-8 -*-
# 工厂方法模式
from abc import ABCMeta, abstractmethod
class Payment(metaclass=ABCMeta):
@abstractmethod
def pay(self, money):
pass
class Alipay(Payment):
def __init__(self, use_huabei=False):
self.use_huabei = use_huabei
def pay(self, money):
if self.use_huabei:
print(f"花呗支付{money}元")
else:
print(f"支付宝支付{money}元")
class WechatPay(Payment):
def pay(self, money):
print(f"微信支付{money}元")
class BankPay(Payment):
def pay(self, money):
print(f"银行卡支付{money}元")
class PaymentFactory(metaclass=ABCMeta):
@abstractmethod
def create_payment(self):
pass
class AlipayFactory(PaymentFactory):
def create_payment(self):
return Alipay()
class WechatPayFactory(PaymentFactory):
def create_payment(self):
return WechatPay()
class HuabeiFactory(PaymentFactory):
def create_payment(self):
return Alipay(use_huabei=True)
class BankPayFactory(PaymentFactory):
def create_payment(self):
return BankPay()
pf = HuabeiFactory()
p = pf.create_payment()
p.pay(100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment