douchi0028 2010-04-04 19:28
浏览 58
已采纳

对象职责 - 列表和项目

My question is more like a theoretical.

Say you have an object, that represents the list of something (articles, pages, accounts etc.)

class ObjCollection 

You have a class, that represents a specific item in collection:

class objItem

I have a problem thinking of a basic responsibilities of each object.

Which class is responsible for creating a new objItem?

Which class is responsible for deleting a objItem? Should it delete itself as a method?


Update 1: Techpriester: Is it ok to use object's constructor as a function to create new item? I think of that like:

class objItem {
    public function __construct($id = 0) {
        if ($id > 0) {
            // load item data...
        } else {
            // make new item...
        }
    }
}

But what if something goes wrong in the code, and instead of passing an $id > 0, it passes 0? In this case a more expected behavior would be an empty object, and not the new one, or am I wrong?

  • 写回答

4条回答 默认 最新

  • duanmu2015 2010-04-04 20:11
    关注

    I know this doesn't answer your question, but since you tagged this as PHP I'm going to assume that it will almost certainly be applied with some sort of database model.

    In that case, it's probably a better idea to do away with 'collections' altogether since if you made each class represent only one object, if you wanted to view 10 blog posts, for example, you would be calling 10 separate SELECT queries each retrieving only an individual database record, because you decided to have the 'BlogPost' class encapsulate its retrieval method.

    The alternative is to let the class represent either one or more records, that way, you only need to run one SELECT query whether you're retrieving 5000 records or only one. Pretty much every object-relational-mapper does this.

    When doing object-oriented programming, it's better to think in terms of behavior or responsibility than whether or not the object is a tangible 'thing'. That's the problem with theoretical discussion of OOP. It's very tempting to use analogies like animals and fruits which have very little relevance to real-world programming.

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

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line