问题中已经给出了设计:一个游泳池有一个环境,它有一个内部游泳池。该任务需要组合而不是继承。
有了这个设计,我们可以发明其他的游泳池形状和环境,并且仍然有游泳池
public interface SwimmingPool {
Surrounding getSurrounding();
Pool getPool();
double getOuterArea();
}
public interface Surrounding extends Shape{
// some methods for surroundings
}
public interface Pool extends Shape {
// some methods for pools
}
public interface Shape {
double getArea();
}
接下来,您为矩形和圆形游泳池创建具体类,并使用这些模块来设计游泳池。
现在,我们创建一个具体的游泳池类:
public SwimmingPoolImpl implements SwimmingPool {
private Surrounding surrounding;
private Pool pool;
public SwimmingPoolImpl(Surrounding surrounding, Pool pool) {
this.surrounding = surrounding;
this.pool = pool;
}
public double getOuterArea() {
return surrounding.getArea() - pool.getArea();
}
public Surrounding getSurrounding() { return surrounding; }
public Pool getPool() { return pool; }
}
想象一下,我们有一个包含几十个不同游泳池和环境的库,我们想要创建一个自定义游泳池:
SwimmingPool customPool = new SwimmingPoolImpl(new OvalSurrounding(), new StarShapedPool());
double pavementArea = customPool.getOuterArea();
而已。现在我们可以维护一个包含不同游泳池和外部区域的库,并立即使用它们来创建游泳池,而无需更改游泳池的实现。这就是组合的好处。