《GOF设计模式》—迭代器 (ITERATOR)—Delphi源码示例:避免限定于一种特定的列表实现(一般迭代)

    技术2026-05-25  8

    示例:避免限定于一种特定的列表实现(一般迭代) 说明: 考虑一个List的变体skiplist会对迭代代码产生什么影响。List的SkipList子类必须提供一个实现Iterator接口的相应的迭代器SkipListIterator。在内部,为了进行高效的迭代,SkipListIterator必须保持多个索引。既然SkipListIterator实现了Iterator,PrintEmployee操作也可用于用SkipList存储的雇员列表。 代码: unit uSkipList; interface uses uList, uListIterator; type     TSkipList = class(TList1)     end;     TSkipListIterator = class(TListIterator)     public         constructor Create(const AList: TList1);         //---         procedure First(); override;         procedure Next(); override;         function IsDone(): Boolean; override;         function CurrentItem(): TObject; override;     end; implementation constructor TSkipListIterator.Create(const AList: TList1); begin     inherited Create(AList); end; procedure TSkipListIterator.First; begin     inherited; end; procedure TSkipListIterator.Next; begin     inherited; end; function TSkipListIterator.IsDone: Boolean; begin     Result := inherited IsDone; end; function TSkipListIterator.CurrentItem: TObject; begin     Result := inherited CurrentItem; end; end. procedure TForm1.Button2Click(Sender: TObject); var     AEmployees: TSkipList;     AIterator: TSkipListIterator; begin     self.Memo1.Clear;     //---     AEmployees := TSkipList.Create;     try         with AEmployees do         begin             Add(TEmployee.Create('111',self.Memo1));             Add(TEmployee.Create('222',self.Memo1));             Add(TEmployee.Create('333',self.Memo1));         end;         //---         AIterator := TSkipListIterator.Create(AEmployees);         PrintEmployees(AIterator);         AIterator.Free;     finally         AEmployees.Free;     end; end;

    最新回复(0)