一.组合的概念
在新类里简单地创建原有类的对象。我们把这种方法叫作“组合”,因为新类由现有类的对象合并而成。我们只是简单地重复利用代码的功能,而不是采用它的形式。
组合也就是一个类的对象是另外一个类的成员,一般的程序都有组合的意味,只不过是基本数据类型是成员变量。
例如:
class Battery
{
private double power = 0.0;
public void chargeBattery(double p)
{
if (this.power < 1.) {
this.power = this.power + p;
}
}
public boolean useBattery(double p)
{
if (this.power >= p) {
this.power = this.power - p;
return true;
}
else {
this.power = 0.0;
return false;
}
}
}
class Torch
{
/**
* composition
*/
private Battery theBattery = new Battery();
/**
* 10% power per hour use
* warning when out of power
*/
public void turnOn(int hours)
{
boolean usable;
usable = this.theBattery.useBattery( hours*0.1 );
if (usable != true) {
System.out.println("No more usable, must charge!");
}
}
/**
* 20% power per hour charge
*/
public void charge(int hours)
{
this.theBattery.chargeBattery( hours*0.2 );
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
上面的new为theBattery对象分配内存,不可或缺。
我们定义Battery类。Torch类使用了一个Battery类型的对象(theBattery)来作为数据成员。在Torch的方法中,我们通过操纵theBattery对象,来实现Battery类所提供的功能(functionality)。
我们说,一个Torch对象拥有(has-a)一个Battery对象。
二.什么时候该用继承,什么时候该用组合?
以下两条原则说明了应该如何选择继承与组合:
- 如果存在一种IS-A的关系(比如Bee“是一个”Insect),并且一个类需要向另一个类暴露所有的方法接口,那么更应该用继承的机制。
- 如果存在一种HAS-A的关系(比如Bee“有一个”attack功能),那么更应该运用组合。
三.组合放在这里只是为了记住这个名词(因为在Thinking in java复用类中看到),其实我们经常用到但可能不知道这叫组合