Abstract Factory(抽象工厂) — 对象创建型模式
简单来说,Abstract Factory 主要将工厂抽象出来,工厂是产品的集合, 也就是说抽象工厂类的实例化是一个工厂,工厂提供产品的具体实现。
适用场景
- 客户端(应用层)不依赖于产品类实例是如何创建,实现等细节。
- 强调一系列相关的产品对象(属于一个产品族)。
- 提供一个产品类库,但只想显示他们的接口而不是实现。
优点
- 产品代码与应用层进行隔离,客户只通过它们的抽象接口来操纵实例。产品的类名也在具体工厂的实现中隔离,即它们不出现在客户代码中。
- 当一个系列的产品对象设计成一起工作时,一个应用一次只能使用同一个系列中的对象,Abstract Factory 很容易办到。
缺点
- 规定了所有可能被创建的产品集合,产品族中扩展新的产品困难。
UML图
示例
class PhoneProduct(object):
def start(self):
raise NotImplementedError
def shutdown(self):
raise NotImplementedError
def callup(self):
raise NotImplementedError
def sendSMS(self):
raise NotImplementedError
class RouterProduct(object):
def start(self):
raise NotImplementedError
def shutdown(self):
raise NotImplementedError
def openWifi(self):
raise NotImplementedError
def setting(self):
raise NotImplementedError
class XiaomiPhone(PhoneProduct):
def start(self):
print("开启小米手机")
def shutdown(self):
print("关闭小米手机")
def callup(self):
print("用小米手机打电话")
def sendSMS(self):
print("用小米手机发短信")
class XiaomiRouter(RouterProduct):
def start(self):
print("开启小米路由器")
def shutdown(self):
print("关闭小米路由器")
def openWifi(self):
print("小米路由器打开wifi")
def setting(self):
print("设置小米路由器")
class HuaweiPhone(PhoneProduct):
def start(self):
print("开启华为手机")
def shutdown(self):
print("关闭华为手机")
def callup(self):
print("用华为手机打电话")
def sendSMS(self):
print("用华为手机发短信")
class HuaweiRouter(RouterProduct):
def start(self):
print("开启华为路由器")
def shutdown(self):
print("关闭华为路由器")
def openWifi(self):
print("华为路由器打开wifi")
def setting(self):
print("设置华为路由器")
class AbstractFactory(object):
def createPhone(self):
raise NotImplementedError
def createRouter(self):
raise NotImplementedError
class XiaomiFactory(AbstractFactory):
def createPhone(self):
print("生产小米手机...")
return XiaomiPhone()
def createRouter(self):
print("生产小米路由器...")
return XiaomiRouter()
class HuaweiFactory(AbstractFactory):
def createPhone(self):
print("生产华为手机...")
return HuaweiPhone()
def createRouter(self):
print("生产华为路由器...")
return HuaweiRouter()
"""
client
"""
if __name__ == "__main__":
print("小米系列 ")
xiaomiFac = XiaomiFactory()
xiaomiPhone = xiaomiFac.createPhone()
xiaomiRouter = xiaomiFac.createRouter()
xiaomiPhone.start()
xiaomiPhone.callup()
xiaomiPhone.sendSMS()
xiaomiPhone.shutdown()
xiaomiRouter.start()
xiaomiRouter.setting()
xiaomiRouter.openWifi()
xiaomiRouter.shutdown()
print("华为系列")
huaweiFac = HuaweiFactory()
huaweiPhone = huaweiFac.createPhone()
huaweiRouter = huaweiFac.createRouter()
huaweiPhone.start()
huaweiPhone.callup()
huaweiPhone.sendSMS()
huaweiPhone.shutdown()
huaweiRouter.start()
huaweiRouter.setting()
huaweiRouter.openWifi()
huaweiRouter.shutdown()
"""
output:
小米系列
生产小米手机...
生产小米路由器...
开启小米手机
用小米手机打电话
用小米手机发短信
关闭小米手机
开启小米路由器
设置小米路由器
小米路由器打开wifi
关闭小米路由器
华为系列
生产华为手机...
生产华为路由器...
开启华为手机
用华为手机打电话
用华为手机发短信
关闭华为手机
开启华为路由器
设置华为路由器
华为路由器打开wifi
关闭华为路由器
"""