吸气剂中重复开关的设计模式?

Jun*_*ter 5 php language-agnostic design-patterns if-statement

对于博客系统,我有一个ORM模型(PHP Active Record).我有一些东西是post存储喜欢的数量的模型.在post既可以是一个picturequote(说),他们是不同的表(因此型号).

模式是a post保存数据,如共享,喜欢,描述等数量以及a picture或a quote.

因此,在为post模型编写getter时,我必须编写

public function getX() {
    if ($this->isPicture()) {
       return $this->picture->getX();
    }
    else if ($this->isQuote()) {
       return $this->quote->getX()
    }
    else {
       return self::DEFAULT_X
    }
}
Run Code Online (Sandbox Code Playgroud)

我目前不得不为许多吸气剂编写这种结构.我能做些什么来避免这种情况吗?

PS:标记为PHP,因为这是我的代码.

编辑

  • 将注释更改为代码.
  • 这是一个模型(以及数据库中的相应表),它拥有的数据多于a picturequote.例如,description这部分post与不驻留在任一picturequote.
  • pictures和quotes 的表格.
  • 使用PHP Active Record和三个类中的每一个都扩展了PHP Active Record提供的通用模型类.
  • picture模型拥有自己的数据.同样的quote.

cmb*_*ley 2

扩展评论中提到的策略模式的想法:

class Post {
    // get the correct 'strategy'
    public function getModel() {
        if ($this->isPicture()) {
            return $this->picture;
        }

        if ($this->isQuote()) {
            return $this->quote;
        }

        return null;
    }

    // using the strategy
    public function getX() {
        $model = $this->getModel();

        if (null === $model) {
            return self::DEFAULT_X;
        }

        return $model->getX();
    }
}
Run Code Online (Sandbox Code Playgroud)

Post每个策略大概都会实现与公开这些 getter 的类相同的接口。更好的是提供默认策略(而不是返回 null)并让它返回默认值。这样,每个 getter 中的 null 检查就变得多余了。