Time will tell.
一、简单的工厂模式
基于一个包含do_say()
方法的 Animal的抽象类创建两个类:Cat、Dog。
from abc import ABCMeta, abstractmethod
class Animal(metaclass=ABCMeta):
@abstractmethod
def do_say(self):
pass
class Dog(Animal):
def do_say(self):
print("Bhow Bhow!!")
class Cat(Animal):
def do_say(self):
print("Meow Meow!!")
创建一个包含make_sound()
方法的工厂类 ForestFactory 。
class ForestFactory(object):
def make_sound(self, object_type):
return eval(object_type)().do_say()
制造点声音:
if __name__ == '__main__':
ff = ForestFactory()
animal = input("Which animal should make_sound?[Dog or Cat]")
ff.make_sound(animal)
运行结果:
类的关系:
二、工厂模式
有两个社交网站 LinkedIn 和 Facebook,它们的个人简介界面有各自不同的内容。
内容抽象类Section
from abc import ABCMeta, abstractmethod
class Section(metaclass=ABCMeta):
@abstractmethod
def describe