工厂模式之工厂方法模式

# 了解
- 我们定义了一个接口来创建对象,但是工厂本身并不负责创建对象,而是将这一任务交由子类来完成,即子类决定了要实例化哪些类。
- Factory方法的创建是通过继承而不是通过实例化来完成的
- 工厂方法使设计更加具有可定制性,它可以返回相同的实例或子类,而不是某种类型的对象(就像在简单工厂方法中的那样)

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

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")
        
我们创建了一个名为Profile的抽象类Creator.Profile[Creator]抽象类提供了一个工厂方法,即createProfile().createProfile()方法应该由ConcreteClass实现,来实现创建带有适当区的简介。Profile抽象类不知道每个简介应具有哪些区。例如,Facebook的简介应该提供个人信息区和相册区。所以我们将让子类来决定这些事情.
我们创建了两个ConcreteCretor类,即linkedin和facebook。每个类都实现creteProfile()抽象方法,由该方法在运行时实际创建(实例化)多个区(ConcreteProducts):
class Profile(metaclass=ABCMeta):
    def __init__(self):
        self.sections = []
        self.createProfile()
    @abstractmethod
    def createProfile(self):
        pass
    def getSections(self):
        return self.sections
    def addSections(self, section):
        self.sections.append(section)
        
 class linkedin(Profile):
    def createProfile(self):
        self.addSections(PersonalSection())
        self.addSections(PatentSection())
        self.addSections(PublicationSection())
        
class facebook(Profile):
    def createProfile(self):
        self.addSections(PersonalSection())
        self.addSections(AlbumSection())
        
        
        
# 优点
- 具有更大的灵活性,使得代码更加通用,因为它不是单纯的实例化某个类,这样,实现哪些类取决于接口,而不是类
- 它们是松耦合的,因为创建对象的代码与使用它的代码是分开的,客户端完全不需要关心要传递哪些参数以及需要实例化哪些类。由于添加新类更加容易,所以降低了维护成本。
posted @ 2022-01-27 15:13  我在路上回头看  阅读(29)  评论(0编辑  收藏  举报