添加抽象工厂模式示例,包含手机和笔记本电脑的具体产品及工厂实现,并更新相关文档和构建脚本
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
"""
|
||||
实例
|
||||
今天伟哥约自己在富士康工作的老乡出来喝酒,没想到老乡最近一直在加班。听说接了个大活,要同时为小米公司和苹果公司代工他们的笔记本电脑和手机生产业务。
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
# 抽象产品 - 手机
|
||||
class Phone(ABC):
|
||||
brand: str
|
||||
|
||||
@abstractmethod
|
||||
def setOS(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
# 具体产品 - 苹果手机
|
||||
class Iphone(Phone):
|
||||
def __init__(self):
|
||||
self.brand = "Apple"
|
||||
|
||||
def setOS(self):
|
||||
print(" 为该手机安装IOS系统")
|
||||
|
||||
|
||||
# 具体产品 - 小米手机
|
||||
class MiPhone(Phone):
|
||||
def __init__(self):
|
||||
self.brand = "Xiaomi"
|
||||
|
||||
def setOS(self):
|
||||
print(" 为该手机安装安卓系统")
|
||||
|
||||
|
||||
# 抽象产品 - 笔记本电脑
|
||||
class Laptop(ABC):
|
||||
brand: str
|
||||
|
||||
@abstractmethod
|
||||
def setOS(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
# 具体产品 - 苹果笔记本电脑
|
||||
class Macbook(Laptop):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.brand = "Apple"
|
||||
|
||||
def setOS(self):
|
||||
print(" 为该笔记本电脑安装macOS系统")
|
||||
|
||||
|
||||
# 具体产品 - 小米笔记本电脑
|
||||
class MiLaptop(Laptop):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.brand = "Xiaomi"
|
||||
|
||||
def setOS(self):
|
||||
print(" 为该笔记本电脑安装Windows系统")
|
||||
|
||||
|
||||
# 抽象工厂
|
||||
class AbstractFactory(ABC):
|
||||
@abstractmethod
|
||||
def createPhone(self) -> Phone:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def createLaptop(self) -> Laptop:
|
||||
pass
|
||||
|
||||
|
||||
# 具体工厂 - 苹果工厂
|
||||
class AppleFactory(AbstractFactory):
|
||||
def createPhone(self):
|
||||
return Iphone()
|
||||
|
||||
def createLaptop(self):
|
||||
return Macbook()
|
||||
|
||||
|
||||
# 具体工厂 - 小米工厂
|
||||
class XiaomiFactory(AbstractFactory):
|
||||
def createPhone(self):
|
||||
return MiPhone()
|
||||
|
||||
def createLaptop(self):
|
||||
return MiLaptop()
|
||||
|
||||
|
||||
def main():
|
||||
print("======== 抽象工厂模式 ========")
|
||||
|
||||
# 伟哥先去苹果工厂生产产品
|
||||
print("伟哥选择了苹果工厂生产产品:")
|
||||
appleFactory = AppleFactory()
|
||||
applePhone = appleFactory.createPhone()
|
||||
appleLaptop = appleFactory.createLaptop()
|
||||
print(f" 生产了一台{applePhone.brand}手机")
|
||||
applePhone.setOS()
|
||||
print(f" 生产了一台{appleLaptop.brand}笔记本电脑")
|
||||
appleLaptop.setOS()
|
||||
|
||||
print("\n切换工厂生产其他品牌的产品...\n")
|
||||
|
||||
# 然后伟哥去小米工厂生产产品
|
||||
print("伟哥选择了小米工厂生产产品:")
|
||||
xiaomiFactory = XiaomiFactory()
|
||||
xiaomiPhone = xiaomiFactory.createPhone()
|
||||
xiaomiLaptop = xiaomiFactory.createLaptop()
|
||||
print(f" 生产了一台{xiaomiPhone.brand}手机")
|
||||
xiaomiPhone.setOS()
|
||||
print(f" 生产了一台{xiaomiLaptop.brand}笔记本电脑")
|
||||
xiaomiLaptop.setOS()
|
||||
|
||||
print("====== 抽象工厂模式结束 ======")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user