python設計模式 - 工廠模式之工廠方法
python 環境
python==3.7.2
工廠方法模式簡介
工廠方法模式Factory Method,又稱多型性工廠模式。在工廠方法模式中,核心的工廠類不再負責所有的產品的建立,而是將具體建立的工作交給子類去做。該核心類成為一個抽象工廠角色,僅負責給出具體工廠子類必須實現的介面,而不接觸哪一個產品類應當被例項化這種細節。
程式碼實現
""" 工廠方法模式 """ class Section(metaclass=ABCMeta): """ 抽象類 """ @abstractmethod def describe(self): """ 抽象方法,子類必須實現 """ pass class Carousel(Section): """ 輪播圖區 """ def describe(self): print("Carousel Section") class PostList(Section): """ 部落格列表區 """ def describe(self): print("Post List Section") class PostDetail(Section): """ 部落格詳情頁 """ def describe(self): print("Post Detail Section") class Footer(Section): """ 底注區 """ def describe(self): print("Footer Section") class Comment(Section): def describe(self): print("Comment Section") class Profile(metaclass=ABCMeta): def __init__(self): self.sections = [] self.create_profile() @abstractmethod def create_profile(self): pass def add_section(self, section): self.sections.append(section) def get_sections(self): return self.sections class HomePage(Profile): def create_profile(self): self.add_section(Carousel()) self.add_section(PostList()) self.add_section(Footer) class DetailPage(Profile): def create_profile(self): self.add_section(Carousel()) self.add_section(PostDetail()) self.add_section(Comment()) self.add_section(Footer()) if __name__ == '__main__': home_page = HomePage() detail_page = DetailPage() print(home_page.get_sections()) print(detail_page.get_sections())