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("花呗支付%d元." % money)
else:
print("支付宝余额支付%d元." % money)
class WechatPay(Payment):
def pay(self, money):
print("微信支付%d元." % money)
# 工厂类
class PaymentFactory:
def create_payment(self, method):
if method == 'alipay':
return Alipay()
elif method == 'wechat':
return WechatPay()
elif method == 'huabei':
return Alipay(use_huabei=True)
else:
raise TypeError('No such payment named %s' % method)
# 客户端
pf = PaymentFactory()
p = pf.create_payment('huabei')
p.pay(100)
花呗支付100元.
使用工厂类进行包装,使得客户端无需了解内部调用的更多细节
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("花呗支付%d元." % money)
else:
print("支付宝余额支付%d元." % money)
class WechatPay(Payment):
def pay(self, money):
print("微信支付%d元." % money)
class BankPay(Payment):
def pay(self, money):
print("银联支付%d元." % 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)
花呗支付100元.
from abc import ABCMeta, abstractmethod
# 抽象产品
class PhoneShell(metaclass=ABCMeta):
@abstractmethod
def show_shell(self):
pass
class CPU(metaclass=ABCMeta):
@abstractmethod
def show_cpu(self):
pass
class OS(metaclass=ABCMeta):
@abstractmethod
def show_os(self):
pass
# 抽象工厂
class PhoneFactory(metaclass=ABCMeta):
@abstractmethod
def make_shell(self):
pass
@abstractmethod
def make_cpu(self):
pass
@abstractmethod
def make_os(self):
pass
# 具体产品
class SmallShell(PhoneShell):
def show_shell(self):
print("普通手机小手机壳")
class BigShell(PhoneShell):
def show_shell(self):
print("普通手机大手机壳")
class AppleShell(PhoneShell):
def show_shell(self):
print("苹果手机壳")
class SnapDragonCPU(CPU):
def show_cpu(self):
print("骁龙CPU")
class MediaTekCPU(CPU):
def show_cpu(self):
print("联发科CPU")
class AppleCPU(CPU):
def show_cpu(self):
print("苹果CPU")
class Android(OS):
def show_os(self):
print("Android系统")
class IOS(OS):
def show_os(self):
print("iOS系统")
# 具体工厂
class MiFactory(PhoneFactory):
def make_shell(self):
return SmallShell()
def make_cpu(self):
return SnapDragonCPU()
def make_os(self):
return Android()
class HuaweiFactory(PhoneFactory):
def make_shell(self):
return BigShell()
def make_cpu(self):
return MediaTekCPU()
def make_os(self):
return Android()
class IPhoneFactory(PhoneFactory):
def make_shell(self):
return AppleShell()
def make_cpu(self):
return AppleCPU()
def make_os(self):
return IOS()
# 客户端
class Phone:
def __init__(self, shell, cpu, os):
self.shell = shell
self.cpu = cpu
self.os = os
def show_info(self):
print("手机信息:")
self.shell.show_shell()
self.cpu.show_cpu()
self.os.show_os()
def make_phone(factory):
shell = factory.make_shell()
cpu = factory.make_cpu()
os = factory.make_os()
return Phone(shell, cpu, os)
p1 = make_phone(IPhoneFactory())
p1.show_info()
手机信息:
苹果手机壳
苹果CPU
iOS系统
from abc import ABCMeta, abstractmethod
class Player:
def __init__(self, face=None, body=None, arm=None, leg=None):
self.face = face
self.body = body
self.arm = arm
self.leg = leg
def __str__(self):
return "%s, %s, %s, %s" % (self.face, self.body, self.arm, self.leg)
class PlayerBuilder(metaclass=ABCMeta):
@abstractmethod
def build_face(self):
pass
@abstractmethod
def build_body(self):
pass
@abstractmethod
def build_arm(self):
pass
@abstractmethod
def build_leg(self):
pass
class SexyGirlBuilder(PlayerBuilder):
def __init__(self):
self.player = Player()
def build_face(self):
self.player.face = "漂亮脸蛋"
def build_body(self):
self.player.body = "苗条身材"
def build_arm(self):
self.player.arm = "细长手臂"
def build_leg(self):
self.player.leg = "大长腿"
class MonsterBuilder(PlayerBuilder):
def __init__(self):
self.player = Player()
def build_face(self):
self.player.face = "丑陋脸蛋"
def build_body(self):
self.player.body = "胖子身材"
def build_arm(self):
self.player.arm = "粗短手臂"
def build_leg(self):
self.player.leg = "短粗腿"
class PlayerDirector: # 控制组装顺序
def build_player(self, builder):
builder.build_face()
builder.build_body()
builder.build_arm()
builder.build_leg()
return builder.player
# 客户端
builder = SexyGirlBuilder()
director = PlayerDirector()
p = director.build_player(builder)
print(p) # 调用__str__方法
漂亮脸蛋, 苗条身材, 细长手臂, 大长腿
补充__new__函数介绍:
面向对象的编程语言,类的实例化都一定包含两个步骤: (1)在内存中创建对象,即开辟一块内存空间来存放类的实例(Instance); (2)初始化对象,即给实例的属性赋予初始值,例如全部填 0;
在 python 中,第一步由__new__函数负责,第二步由__init__函数负责。
class Singleton:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = super().__new__(cls)
return cls._instance
class MyClass(Singleton):
def __init__(self, s):
self.s = s
a = MyClass(10)
b = MyClass(20)
print(a.s)
print(b.s)
print(id(a), id(b))
20
20
1506330511680 1506330511680