形状工厂

题目描述:工厂模式是一种常见的设计模式。实现一个形状工厂 ShapeFactory 来创建不同的形状类。这里我们假设只有三角形,正方形和矩形三种形状。

样例:


考察对类的设计和类的方法的实现。

由题目要求可知,我们首先要定义一个类:Shape,这个类作为三角形,正方形和矩形的父类,然后再定义三个由Shape这个类派生出来的子类:Triangle,Rectangle,Square,这三个类都有他们各自的方法,比如题目中要求的打印出形状。最后,再定义一个ShapeFactory类,调用刚才为上面三种形状的类所定义的方法。这个没什么逻辑上的难度,直接实现就行。

代码如下:

"""
Your object will be instantiated and called as such:
sf = ShapeFactory()
shape = sf.getShape(shapeType)
shape.draw()
"""
class Shape:
    def draw(self):
        raise NotImplementedError('This method should have implemented.')


class Triangle(Shape):
    def draw(self):
        print("  /\\")
        print(" /  \\")
        print("/____\\")
    # Write your code here


class Rectangle(Shape):
    def draw(self):
        print(" ---- ")
        print("|    |")
        print(" ---- ")
    # Write your code here


class Square(Shape):
    def draw(self):
        print(" ---- ")
        print("|    |")
        print("|    |")
        print(" ---- ")
    # Write your code here


class ShapeFactory:
    # @param {string} shapeType a string
    # @return {Shape} Get object of type Shape
    def getShape(self, shapeType):
        if shapeType == "Square":
            return Square()
        if shapeType == "Rectangle":
            return Rectangle()
        if shapeType == "Triangle":
            return Triangle()
        # Write your code here


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值