题目描述:工厂模式是一种常见的设计模式。请实现一个玩具工厂 ToyFactory 用来产生不同的玩具类。可以假设只有猫和狗两种玩具。
样例:
做法跟上一道题“形状工厂”(详见:点击打开链接)是一致的,甚至还要更简单一些,基本的做法我在“形状工厂”中已经讲解过,此处省略,直接给出代码:
"""
Your object will be instantiated and called as such:
ty = ToyFactory()
toy = ty.getToy(type)
toy.talk()
"""
class Toy:
def talk(self):
raise NotImplementedError('This method should have implemented.')
class Dog(Toy):
def talk(self):
print("Wow")
# Write your code here
class Cat(Toy):
def talk(self):
print("Meow")
# Write your code here
class ToyFactory:
# @param {string} shapeType a string
# @return {Toy} Get object of the type
def getToy(self, type):
if type == "Dog":
return Dog()
elif type == "Cat":
return Cat(Toy)
# Write your code here