标签:lse 结构 顺序 模式 长度 virtual public iterator agg
1) 意图
提供一种方法顺序访问一个聚合对象中的各个元素,且不需要暴露该对象的内部表示
2) 结构
其中:
3) 适用性
4) 举例
1 #include <iostream> 2 typedef int DATE; 3 class Iterator 4 { 5 public: 6 Iterator() {} 7 virtual ~Iterator() {} 8 virtual void First() = 0; // 迭代器归零 9 virtual void Next() = 0; // 迭代器指向下一个 10 virtual bool IsDone() = 0; // 迭代器已指向最后一个元素 11 virtual DATE Currentltem() = 0; // 迭代器当前指向的元素 12 }; 13 14 class Aggregate 15 { 16 public: 17 Aggregate() {}; 18 virtual ~Aggregate() {} 19 virtual Iterator* CreateIterator() = 0; 20 virtual int getSize() = 0; 21 virtual DATE getItem(int index) = 0; 22 virtual void push_back(DATE date) = 0; 23 }; 24 class ConcreteIterator : public Iterator 25 { 26 public: 27 ConcreteIterator(Aggregate* ptr) : m_pAggregate(ptr) 28 ,m_index(0) 29 { 30 } 31 virtual ~ConcreteIterator() {} 32 virtual void First() 33 { 34 m_index = 0; 35 } 36 virtual void Next() 37 { 38 m_index++; 39 } 40 virtual bool IsDone() 41 { 42 if (m_index == m_pAggregate->getSize()) 43 { 44 return true; 45 } 46 return false; 47 } 48 virtual DATE Currentltem() 49 { 50 return m_pAggregate->getItem(m_index); 51 } 52 private: 53 int m_index; 54 Aggregate* m_pAggregate; 55 }; 56 class ConcreteAggregate : public Aggregate 57 { 58 public: 59 ConcreteAggregate(int num) : m_size(num), m_index(0) 60 { 61 m_start = new DATE[num]; 62 } 63 virtual ~ConcreteAggregate() 64 { 65 delete[] m_start; 66 } 67 virtual Iterator* CreateIterator() 68 { 69 return new ConcreteIterator(this); 70 } 71 void push_back(DATE date) 72 { 73 if (m_index < m_size) 74 { 75 *(m_start+m_index) = date; 76 m_index++; 77 } 78 } 79 virtual int getSize() 80 { 81 return m_index; 82 } 83 virtual DATE getItem(int index) 84 { 85 return *(DATE*)(m_start+index); 86 } 87 private: 88 DATE* m_start; // 目前使用空间的头 89 int m_index; 90 int m_size; // 申请空间长度 91 }; 92 93 int main() 94 { 95 Aggregate* pAggregate = new ConcreteAggregate(2); 96 97 pAggregate->push_back(1); 98 pAggregate->push_back(2); 99 Iterator* iter = new ConcreteIterator(pAggregate); 100 for (; !iter->IsDone(); iter->Next()) 101 { 102 std::cout << iter->Currentltem() << std::endl; 103 } 104 delete pAggregate; 105 delete iter; 106 system("pause"); 107 }
标签:lse 结构 顺序 模式 长度 virtual public iterator agg
原文地址:https://www.cnblogs.com/ho966/p/12235313.html