dongpo2340 2013-04-26 12:43
浏览 80

php - 使用对象组合重构一个类

I recently had some time to refactor an old personal project and i wanted to use it as a learning experience on how to best deal with this kind of class.

The problem is my class (item) has 2 genders associated with it (and in the future may have more like a poster of the item, and hats/accessories of the item), each of these genders uses nearly identical methods to get and set things about them (get_productImage, set_price, etc).

I wanted to refactor the class so that instead of using a male and female counterpart for each function, i could have the code written once, and use it twice (or more). Here is (a very simplified example of) what i have so far:

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.
    }
}

Is there a way that i can re-write this better? The other problem i have is that the displayDate can (and will be) changed and shuffled around a lot so any changes to it need to be propagated to the gender class as well which is going to make this a huge mess...

If it helps, i am using php 5.4 so any new things added to that can be used here as well.

  • 写回答

1条回答 默认 最新

  • doulao1966 2013-04-26 13:02
    关注

    I see two general ways of solution.

    One is that you glue both genders on single class and distinguish between male/female with some kind of flag (for example, 'type' of you plan to have more than two genders).

    Another is using traits.

    For example, you know that $displayDate is always being get/set and treated the same way. So you make a trait, say, hasDisplayDate, where you specify property (protected $displayDate) and all the necessary methods. And in genders you just add 'use hasDisplayDate' to admix the trait. You can overload methods that are present in traits when you need.

    评论

报告相同问题?

悬赏问题

  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率