Design Patterns - Factory Method

Factory Method(工厂方法) — 对象创建型模式

定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类(抽象工厂模式中就使用到了工厂方法)

适用场景

  1. 当一个类不知道它所必须创建的对象的类的时候
  2. 当一个类希望由它的子类来指定它所创建的对象的时候

优点

  1. 工厂方法不再将与特定应用有关的类绑定到你的代码中。代码仅处理 Product 接口,因此它可以与用户定义的任何 COncreteProduct 类一起使用。

缺点

  1. 创建一个特定的 ConcreteProduct 对象,就不得不创建 Creator 的子类。

其他一些需要考虑的问题

  1. Factory Method 模式主要有两种不同的情况:1. Creator 类是一个抽象类并且不提供它所声明的工厂方法的实现;2. Creator 是一个具体的类而且为工厂方法提供一个缺省的实现。第一种情况需要子类来定义实现,因为没有合理的缺省实现。它避免了不得不实现不可预见类的问题。在第二种情况下,你也可以在必要时重载父类。
  2. 参数化工厂方法,有些情况下可以使一个Creator创建多个产品,即采用一个标识作为要被创建的对象种类的参数。
class Creator {
    public:
        virtual Product *Create(ProductId);
};

Product* Creator::Create (ProductId id) {
    if (id == MINE) return new MyProduct;
    if (id == YOURS) return new YourProduct;
    // repeat for remaining productes...

    return 0;
}

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 XiaomiPhone(PhoneProduct):
    def start(self):
        print("开启小米手机")

    def shutdown(self):
        print("关闭小米手机")

    def callup(self):
        print("用小米手机打电话")

    def sendSMS(self):
        print("用小米手机发短信")

class HuaweiPhone(PhoneProduct):
    def start(self):
        print("开启华为手机")

    def shutdown(self):
        print("关闭华为手机")

    def callup(self):
        print("用华为手机打电话")

    def sendSMS(self):
        print("用华为手机发短信")

class Creator(object):
    def createPhone(self):
        raise NotImplementedError
    
    def work(self):
        phone = self.createPhone()
        phone.start()
        phone.callup()
        phone.sendSMS()
        phone.shutdown()
        
    
class XiaomiPhoneCreator(Creator):
    def createPhone(self):
        return XiaomiPhone()

class HuaweiPhoneCreator(Creator):
    def createPhone(self):
        return HuaweiPhone()
    


client

creator = XiaomiPhoneCreator()
creator.work()
print("****************")
creator = HuaweiPhoneCreator()
creator.work()

"""output
开启小米手机
用小米手机打电话
用小米手机发短信
关闭小米手机
****************
开启华为手机
用华为手机打电话
用华为手机发短信
关闭华为手机
"""
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值