一个工厂类收录了所有的类创建逻辑,让用户不需要关心类的创建,只专注与类的使用。
# 抽象产品,具体产品,工厂
# 手机店,可以卖各种手机。
import abc
class Phone(metaclass=abc.ABCMeta):
def call(self):
pass
def do_explore(self):
pass
class MiPhone(Phone):
def call(self):
print("小米手机打电话")
def do_explore(self):
print("小米手机上网")
class IPhone(Phone):
def call(self):
print("iphone手机打电话")
def do_explore(self):
print("iphone手机上网")
class LenovoPhone(Phone):
def call(self):
print("联想手机打电话")
def do_explore(self):
print("联想手机上网")
class PhoneShop():
@staticmethod
def create_phone(phone_type):
if phone_type == "MiPhone":
return MiPhone()
elif phone_type == "Iphone":
return IPhone()
else:
return LenovoPhone()
if __name__ == "__main__":
phone = PhoneShop.create_phone("Iphone")
phone.call()
phone.do_explore()