学习笔记02--工厂方法模式

以下几点能帮助理解工厂方法模式:

  1. 定义一个接口来创建对象,但是工厂本身并不负责创建对象,而是将这一任务交由子类来完成,即子类决定了要实例化哪些类
  2. Factory方法的创建是通过继承而不是通过实例化来完成的
  3. 工厂方法使设计更加具有可定制性。它可以返回相同的实例或子类,而不是某种类型的对象。

ps:可以理解为,工厂方法模式中,工厂提供零件和组装零件的方法,至于组装成什么产品,由子类自定义

如下UML图中,有一个包含factoryMethod()方法的抽象类Creator,factoryMethod()方法创建指定类型的对象。ConcreteCreator类提供了一个实现Creator抽象类的factoryMethod()方法,这种方法可以在运行时修改已创建的对象。ConcreteCreator创建ConcreteProduct,并确保其创建的对象实现了Product类,同时为Product接口中的所有方法提供相应的实现。

1. 实现工厂方法

拿一个现实世界的场景做例子。假设我们想在不同类型的社交网络(例如LinkedIn,Facebook等)上为个人或公司建立简介。那么,每个简介都有某些特定的组成章节。在LinkedIn的简介中,有一个章节是关于个人申请的专利或出版社作品的。在Facebook上,你将在相册看到最近度假地点的照片区。此外,在两个简介中,都有一个个人信息区。简而言之,我们要通过将正确的区添加到相应的简介中来创建不同类型的简介。

from abc import ABCMeta, abstractmethod

class Section(metaclass=ABCMeta):
    @abstractmethod
    def describe(self):
        pass
        
class PersonalSection(Section):
    def describe(self):
        print('Personal Section')
        
class AlbumSection(Section):
    def describe(self):
        print('Album Section')
        
class PatentSection(Section):
    def describe(self):
        print('Patent Section')
        
class PublicationSection(Section):
    def describe(self):
        print('Publication Section')
   
# Creator     
class Profile(metaclass=ABCMeta):
    def __init__(self):
        self.sections = []
        self.createProfile()
        
    # factoryMethod()
    @abstractmethod
    def createProfile(self):
        pass
    
    def getSections(self):
        return self.sections
    
    def addSections(self, section):
        self.sections.append(section)
     
# ConcreteCreator   
class linkedin(Profile):
    def createProfile(self):
        self.addSections(PersonalSection())
        self.addSections(PatentSection())
        self.addSections(PublicationSection())
    
# ConcreteCreator    
class facebook(Profile):
    def createProfile(self):
        self.addSections(PersonalSection())
        self.addSections(AlbumSection())
        
if __name__ == '__main__':
    profile_type = input('Which Profile you would like to create? [LinkedIn or FaceBook]')
    profile = eval(profile_type.lower())()
    print('Creating Profile...', type(profile).__name__)
    print('Profile has sections --', profile.getSections())

首先,创建一个Section抽象类,提供一个抽象方法describe(),然后创建PersonalSecton, AlbumSection, PatentSection和PublicationSection类,这些类用于实现describe()方法。接着,创建一个Profile抽象类(Creator),提供一个工厂方法(factoryMethod)即createProfile()。再创建两个ConcreteCreator类即linkedin和facebook,每个类都实现了createProfile()方法,此方法可以在运行时创建多个ConcreteProducts

2. 工厂方法模式的优点

  1. 具有更强大的灵活性,使得代码更加通用,因为它不是单纯的实例化某个类。
  2. 松耦合,因为创建对象的代码与使用它的代码是分开的。客户端完全不用关心传递哪些参数以及需要实例化哪些类。由于添加新类更加容意,所以降低了维护成本。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值