玩具工厂

题目描述:工厂模式是一种常见的设计模式。请实现一个玩具工厂 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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值