dongyuan1160 2015-09-07 16:56
浏览 20

有一个与此解决方案相关的设计模式吗?

There is a solution that I use frequently, I would like to know if there is an design pattern that is related to this solution:

I want modify properties of an object, and i would like to separate each responsability in different classes and also be able to add/remove easier those responsabilities.

There is Pattern to name this solution? It is a good solution or there is another pattern this fix it better?

Thank you!

class Choice 
{
    private $isSelected;

    private $isRight; 
}

class ChoiceModifierInterface
{
    public function modify();
}

class Selector
{
    public function modify(Choice $choice)
    {
        //check if the user select the question 
        $choice->isSelected(true);
    }
}

class Corrector
{
public function modify(Choice $choice)
    {
        //check if the question is right
        $choice->isRight(true);
    }
}


class ChoiceModifier
{
    public function add(ModifierInterface $modifier)
    {
        //add classes
    }

    public function modify(Choice $choice)
    {
        foreach ($this->modifiers as $modifier)
        {
            $modifier->modify($choice);
        }
    }
}

class Client
{
    public function main()
    {
        $choiceModifier = new ChoiceModifier();
        $choiceModifier->add(//add all modifiers);

        //run all modifiers
        $choiceModifier->modify($choice);
    }
}
  • 写回答

1条回答 默认 最新

  • dsb238100 2015-09-08 11:38
    关注

    I'm not a PHP developer but it looks to be Composite pattern.

    The way I usually use Composite patter is for example with logging. When I want to log to multiple places at the same time (like file, some cloud error tracking system, debug window and maybe more) I create single logger abstraction then I implement this abstraction in all my loggers and create Composite logger. Composite logger logger also implements logger interface and it contains collection of all other loggers. The only responsibility of Composite logger is to delegate the invocation to all loggers it contains. This way you can log to multiple places with just one invocation in the client code.

    I never used composite patter to modify objects state but I can imagine that in certain scenarios it might be a good solution.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分