用对象组合重构类


refactoring a class with object composition

我最近有一些时间重构一个旧的个人项目,我想把它作为学习如何最好地处理这种类的经验。

问题是我的类(物品)有两种性别与之相关(将来可能会有更多的物品海报,物品的帽子/配件),每一种性别都使用几乎相同的方法来获取和设置关于它们的东西(get_productImage, set_price等)。

我想重构这个类,这样我就可以编写一次代码,然后使用两次(或更多次),而不是为每个函数使用男性和女性对应的对象。以下是我目前所拥有的(一个非常简单的例子):

class Item
{
    public $ID, $displayDate;
    public $male, $female;
    public function __construct($ID)
    {
        //Fancy code to initialize stuff like $displayDate
        $male = new Gender('male', $ID, $displayDate);
        $female = new Gender('female', $ID, $displayDate);
    }
}
class Gender
{
    private $ID, $displayDate;
    public function get_currentPrice()
    {
        //The current price of the gender changes based on the display date vs the current date and then adjusts the price accordingly and returns it.
    }
}

有什么方法可以重写得更好吗?另一个问题是,我有displayDate可以(并将)改变和周围洗牌很多,所以任何改变它需要传播到性别类,以及这将使这一个巨大的混乱…

如果它有帮助,我使用php 5.4所以任何新的东西添加到这里也可以使用

我看到了两种一般的解决方法。

一种是你把两种性别都粘在一个类上,并用某种标志来区分男性/女性(例如,你计划有两个以上性别的"类型")。

另一个是使用特征。

例如,您知道$displayDate总是以相同的方式获取/设置和处理。所以你创建一个trait,比如hasDisplayDate,在这里你指定属性(protected $displayDate)和所有必要的方法。在性别中,你只需要添加'use hasDisplayDate'来添加性状。当你需要的时候,你可以重载trait中的方法。