background image

不过,保持这两个类的独立却是有意义的。这样,不仅为我们最大限度地提供了灵活性和
可重用性,同时也减少了重复的代码。因此,我们可以考虑另一个规则——“有一个”规则
是否适用。因为 Person“有一个”Address,所以将这两个类聚合起来是有意义的。

通过聚合,可以将一个对象作为其他一个或多个对象的容器。这也是解决多重继承问题的
另一种方案,因为我们很容易就可以把一些较小的组件拼合成一个对象。

例如,一个 Person 类可以包含一个 Address 对象。显然,人可以有地址这么一个属性。
然而,并非只有人才有地址属性——商店或者其他机构也可以有地址。因此,与其在
Person 类中硬编码一个地址属性,不如创建一个独立的 Address 类使其能被更多的类
使用才更有意义。

下例展示了按照以上分析编写的代码:

classAddress {
protected$city;
publicfunctionsetCity($city) {
$this->city =$city;
}
publicfunctiongetCity() {
return$this->city;
}
}
classPerson {
protected$name;
protected$address;
publicfunction__construct() {
$this->address =newAddress;
}
publicfunctionsetName($name) {
$this->name =$name;
}
publicfunctiongetName() {
return$this->name;
}
publicfunction__call($method,$arguments) {
if(method_exists($this->address,$method)) {
returncall_user_func_array(
array($this->address,$method),$arguments);
}
}
}

其中,Address 类用于存储城市信息,并带有两个用于数据读写的访问器方法 ——
setCity()和 getCity()