【问题标题】:choosing a datastructure for a collection of dated objects为数据对象集合选择数据结构
【发布时间】:2011-01-27 22:39:46
【问题描述】:

我正在尝试设计一个 PHP 对象(称为Incident_Collection),它将包含其他对象的集合,每个对象都实现一个Incident 接口。

<?php
class Foo implements Incident {
  protected $incident_date; //DateTime object
  protected $prop1;
  protected $prop2;
  //etc

  public function when(){ //required by Incident interface
    return $this->incident_date;
  }

}
?>

起初我想我只是让我的 Incident_Collection 实现 IteratorAggregate 并将 Incident 对象存储在集合的数组属性中:

<?php
class Incident_Collection implements IteratorAggregate {
  protected $collection=array();

  public function getIterator(){
    return new ArrayIterator($this->collection);    
  }

  public function sort(){
     //sort by $incident->when() values in $this->collection
  }

  /*also __get($var), __set($var,$value), add(Incident $object), remove(Incident $object) and other functions*/
}
?>

但是因为Incident 对象具有自然顺序,我认为扩展SPL Data Structures 之一可能更合适/更有效。 但是哪个?我不太清楚何时使用特定的数据结构。

另一个问题是Incident_Collection 可能存在限制。例如,如果有一个 Person 对象拥有一个 Incident_Collection,那么可能会应用以下限制:

  • 只有 1 个Birth 事件
  • 如果Birth存在,则一定是集合中最早的事件
  • 只有 1 个Death 事件
  • 如果存在Death,则它必须是集合中的最后一个事件
  • HS_Graduation 必须在 HS_Begin 之后

最好有一个通用的Incident_Collection 接受其所有者的一组限制(例如Person),还是一个子类Person_Incident_Collection

【问题讨论】:

    标签: php data-structures date spl


    【解决方案1】:

    退房

    它很好地概述了 SPL 数据结构、它们是什么以及何时使用它们。还有基准。

    如果这是一个对象集合,我肯定会考虑使用 SplObjectStorage 而不是普通的 Array。如果事件应该是 LIFO 或 FIFO 顺序,请考虑队列和堆栈。如果您需要自定义订单,请考虑Priority Queue

    关于限制,您可以使用State Pattern,例如通过通用 IncidentCollection 进行访问,但根据它的所有者属性,应用一个子类来处理状态更改。但是,这要求集合具有所有者属性。因为各个状态都是 IncidentCollection 的子类,所以您也可以直接使用它们。

    【讨论】:

    • 看起来优先队列是我的人。我一直在思考 State 模式,想知道它是否在给百合镀金。很高兴知道您的想法。
    • @dnagirl 不客气。 Re State Pattern 我会根据所有者是否真的是 IncidentCollection 的实际状态(而不是参考/链接)或者它是否是一个特殊情况来决定。如果是后者,我不会使用 State。不知道如何让它变得不那么模糊。对不起:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    • 2011-12-23
    相关资源
    最近更新 更多