douzhi1972 2012-12-18 21:16
浏览 27
已采纳

PHP OOP设计:一个对象可以有几个“模式”。 我该如何定义它们?

I have a Display object that handles HTML output of the script. It has a mode property, which defines many aspects of how the output is generated. There are several modes, and I will probably add more later. Each mode implies it's own parameters. For example, an author mode would imply an authorID. A search mode would imply a Search object as a parameter, which would contain query information. A comment mode would imply a postID and commentID parameters.

So, a mode has a name and some number of parameters, depending on the name.

I decided to create a Display_Mode object, which has two properties: name and parameters. But how do I assign parameters to names? So that if I have a comment mode, it would neccessarily mean that there are postID and commentID parameters?

My current solution is this:

class display_mode{
    public $name;
    public $params;

    public function __construct($name)
        {
        $this->name = $name;
        switch ($this->name){
            case 'comment':
                $this->params = array('postID', `commentID`);
                break;
            case 'author':
                $this->params = array('authorID');
            }
            //etc..
        }
    }

This seems a bit messy. Is there a better way?

UPD: given answers led me to ask another question, concerning the whole design, which also provides context for this one.

  • 写回答

3条回答 默认 最新

  • drv13270 2012-12-18 21:18
    关注

    You're better off abstracting the common functionality of the Display_Mode class into an abstract base class or interface and then defining each individual mode as a class that inherits from the base class (or implements the interface).

    These specialised mode classes would then explicitly define the parameters they require in their constructors and/or methods, and would be responsible for producing the output that each "mode" requires.

    It's difficult to give more specific advice than this without knowing exactly what your Display_Mode class is supposed to do, however.


    The idea here is that you should avoid do-it-all classes in OOP, preferring small, self-contained classes each with a single purpose. By giving each mode its own class that can independently render its content, you're making it easy to change the way display modes work or add new ones. All you have to do is add a new class.

    This is known as loose coupling.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制