请考虑以下类比:如果我们有一个类:"Car",我们可能会期望它有一个"Engine"实例.如:"汽车HAS-A发动机".类似地,在"引擎"类中,我们期望"启动系统"或"冷却系统"的实例各自具有其适当的子组件.
根据封装的性质,汽车"HAS-A""散热器软管"和发动机不是真的吗?
因此,做这样的事情是否合适:
public class Car {
private Engine _engine;
public Engine getEngine() {
return _engine;
}
// is it ok to use 'convenience' methods of inner classes?
// are the following 2 methods "wrong" from an OO point of view?
public RadiatorHose getRadiatorHose() {
return getCoolingSystem().getRadiatorHose();
}
public CoolingSystem getCoolingSystem() {
return _engine.getCoolingSystem();
}
}
public class Engine {
private CoolingSystem _coolingSystem;
public CoolingSystem getCoolingSystem() {
return _coolingSystem;
}
}
public class CoolingSystem {
private RadiatorHose _radiatorHose;
public RadiatorHose getRadiatorHose() {
return _radiatorHose;
}
}
public class RadiatorHose {//...
}
Run Code Online (Sandbox Code Playgroud)