如何为多态模型

时间:2016-05-24 10:24:03

标签: php oop model-view-controller

我需要在不同情况下渲染多态模型。

模特的基类:

abstract class BaseDiscount {
  abstract public function createRenderer(IDiscountRendererFactory $factory);
}

IDiscountRendererFactory:

interface IDiscountRendererFactory {

  /**
   * @return IDiscountRenderer
   */
  public function createDiscountRenderer(Discount $model);

  /**
   * @return IDiscountRenderer
   */
  public function createActionRenderer(Action $model);
}

折扣模型类:

class Discount extends BaseDiscount {
  public function createRenderer(IDiscountRendererFactory $factory) {
    return $factory->createDiscountRenderer($this);
  }
}

动作模型类:

class Action extends BaseDiscount {
  public function createRenderer(IDiscountRendererFactory $factory) {
    return $factory->createActionRenderer($this);
  }
}

IDiscountRenderer:

interface IDiscountRenderer {
  public function render();
}

在客户端模块中我有:

class ConcreteDiscountRenderer implements IDiscountRenderer {
  public function __construct(Discount $model) {
    //do something
  }

  public function render() {
    //do something
  }
}

class ConcreteActionRenderer implements IDiscountRenderer {
  public function __construct(Action $model) {
    //do something
  }

  public function render() {
    //do something
  }
}

class ConcreateDiscountRendererFactory implements IDiscountRendererFactory {
  public function createDiscountRenderer(Discount $model) {
    return new ConcreteDiscountRenderer($model);
  }
  public function createActionRenderer(Action $model) {
    return new ConcreteActionRenderer($model);
  }
}

$repository = new DiscountRepository();

/** @var BaseDiscount[] $discounts */
$discounts = $repository->findAll();
$factory = new ConcreateDiscountRendererFactory();

foreach ($discounts as $discount) {
  $discount->createRenderer();
  $renderer = $discount->createRenderer($factory);
  $renderer->render();
}

在其他应用程序中,部分可能是其他实现。

我想我有一些Visitor和AbstractFactory模式的组合。 这是一种正确的方法还是有更好的解决方案?

UPD

如果我添加新的模型类,比如DiscountProgramm扩展BaseDiscout,我必须重构IDiscountFactoryInterface及其所有实现。有没有办法可以避免这种情况?

0 个答案:

没有答案