题目描述:工厂模式是一种常见的设计模式。实现一个形状工厂 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
这篇博客探讨了工厂模式在设计中的应用,通过创建一个ShapeFactory来实例化不同类型的形状,包括Triangle、Rectangle和Square。每个形状类都有其特定的方法,如打印形状。博客内容围绕面向对象设计,讲解如何定义基类Shape及其派生类,并通过ShapeFactory进行对象的创建和操作。
1365

被折叠的 条评论
为什么被折叠?



