所以我被要求在面试中重构这段代码
有一个Shape抽象类.Square,Rectangle这是派生类Shape.Square和Rectangle覆盖的方法area()的Shape.现在我如何重构这样的代码?
if(object is of type Square) {
//call area on square
} else if (object is of type Rectangle) {
//call area of rectangle
} else if(object of type Cube) {
// call volume of cube
}...
.
.
.
Run Code Online (Sandbox Code Playgroud)
问题基本上是如何避免多个if条件,因为可以有很多派生类并在该对象上调用适当的方法?
啊,现在我明白他想听到的可能是你可以添加另一个抽象类,比如说AbstractFlatShapes
然后检查
if (object is instance of AbstractFlatShapes){
//call area
}else{
//call volume
}
Run Code Online (Sandbox Code Playgroud)
让自己清楚
AbstractFlatShapes延伸Shape
我很确定他想听到这个.想象一下,有15个扁平形状,你会else if为每个形状做什么?调用相同的功能.