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())
网友评论