ITERATOR Патерн поведінки Доповідач: Пропой Ярослав Рецензент: Мельниченко Владислав 0/40 NEXTSTART.

Slides:



Advertisements
Similar presentations
Recursion.
Advertisements

1 Linked lists Sections 3.2, 3.3, 3.5 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors.
Lists A list is a finite, ordered sequence of data items. Important concept: List elements have a position. Notation: What operations should we implement?
Computer Science 112 Fundamentals of Programming II List Iterators.
ArrayLists The lazy mans array. Whats the matter here? int[] list = new int[10]; list[0] = 5; list[2] = hey; list[3] = 15; list[4] = 23;
1 Data Structures - CSCI 102 CS102 C++ Operator Overloading Prof Tejada.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Esempio Polimorfismo1 // Definition of abstract base class Shape #ifndef SHAPE_H #define SHAPE_H class Shape { public: virtual double area() const { return.
LINKED QUEUES P LINKED QUEUE OBJECT Introduction Introduction again, the problem with the previous example of queues is that we are working.
Патерн (принцип) IOC&DI IoC2 Spring Framework.
Патерн (принцип) IOC&DI 2010 (Курс “Інформаційні технології”)
Design Patterns in JDK Collections Christine Bouamalay SBC Services, San Ramon, CA.
Iterators T.J. Niglio Computer & Systems Engineering Fall 2003 Software Design & Documentation Object Behavioral.
Tirgul OOP No.3 Iterators. What is an Iterator? An object that provides a way to access elements of an aggregate object sequentially, without exposing.
Stacks  Standard operations: IsEmpty … return true iff stack is empty Top … return top element of stack Push … add an element to the top of the stack.
Створення макросів в автоматичному режимі
Загальна характеристика
1 Учитель біології Олешко О.О. Кровоносно – судинна система.
ОПЕРАЦІЙНА СИСТЕМА Windows Встановіть відповідність 
What is the out put #include using namespace std; void main() { int i; for(i=1;i
Google App Engine for Java Google App Engine2 Google App Engine (GAE) – це інфраструктура хмарних обчислень, яка орієнтована на підтримку веб-додатків.
Recursion Examples Fundamentals of CS Case 1: Code /* Recursion: Case 1 */ #include void count (int index); main () { count (0); getchar(); } void count.
Chapter 6 Array-Based Lists.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
LinkedList Many slides from Horstmann modified by Dr V.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
Linked Lists Ellen Walker CPSC 201 Data Structures Hiram College.
CHAPTER 5 ArrayLists.
До використання COM- об’єктів у Visual Studio (C#)
2014-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Behavioral Pattern: Iterator C h a p t e r 5 – P a g e 159 Software can become difficult to manage when a variety of different traversals of a variety.
Web-framework Tapestry 2008 (Курс “Інформаційні технології”)
Google Web Toolkit (GWT). AJAX-додатки
Google Web Toolkit (GWT). AJAX-додатки
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
M180: Data Structures & Algorithms in Java Linked Lists – Part 2 Arab Open University 1.
Навчальний елемент Робота з меню у програмі Windows'95 Назва: Оператор комп’ютерного набору Професія: UA002 Код:
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
Списки типів Нікітін Олексій. Навіщо потрібні списки типів? Розглянемо шаблон Abstract Factory. class WidgetFactory { public: virtual Window* createWindow()
Iteration Abstraction SWE Software Construction Fall 2009.
Lecture 9: Lists MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture we will learn…. ArrayList – These are re-sizeable.
Print Row Function void PrintRow(float x[ ][4],int i) { int j; for(j=0;j
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
CS 162 Intro to Programming II Sorting Introduction & Selection Sort 1.
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
Recursive Objects Singly Linked List (Part 2) 1. Operations at the head of the list  operations at the head of the list require special handling because.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Iterator と Adaptor デザインパターン 第1回
The List ADT Reading: Textbook Sections 3.1 – 3.5
Announcements & Review
Lecture 15: More Iterators
null, true, and false are also reserved.
Programming in Java Lecture 11: ArrayList
The List ADT Reading: Textbook Sections 3.1 – 3.5
(Java Collections Framework) AbstractSequentialList
COMPUTER 2430 Object Oriented Programming and Data Structures I
CSE 143 Lecture 27: Advanced List Implementation
Iterator.
ArrayLists.
Design Patterns Difficult to describe abstractly Elements:
Chapter 6 Array-Based Lists.
JCF Collection classes and interfaces
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
Example 1 Ask the user to type10 integers of an array T1 and 10 integers of an array T2. Put into T3, an array with 20 integers : the sum of the elements.
The Sequential Search (Linear Search)
Java Generics & Iterators
Data Structures & Programming
Presentation transcript:

ITERATOR Патерн поведінки Доповідач: Пропой Ярослав Рецензент: Мельниченко Владислав 0/40 NEXTSTART

INTRO Патерн Iterator – це спосіб послідовного доступу до всіх елементів об’єкта – складника не порушуючи інкапсуляції. 1/40 NEXTPREV

MOTIVATION Пункт зверху Для підтримки різних активних обходів одного агрегованого об’єкту Для представлення єдиного інтерфейсу для обходу різних агрегованих структур 2/40 NEXTPREV

2 WAYS Хто керує Ітеруванням? Внутрішня ітерація. Зовнішня ітерація. 3/40 NEXTPREV

SIMPLE 4/40 NEXTPREV

SIMPLE 5/40 NEXTPREV

LIST //interface template class List { public: //велика трійка List (long size = DEFAULT_LIST_CAPACITY) long Count() const; Item & Get(long index) const; //... }; 6/40 NEXTPREV

ITERATOR //interface template class Iterator { public: virtual void First() = 0; virtual void Next() = 0; virtual void IsDone() const = 0; virtual void CurrentItem() const = 0; //… protected: Iterator(); }; 7/40 NEXTPREV

LISTITERATOR //interface template class ListIterator: public Iterator { public: ListIterator(const List * aList); virtual void First() ; virtual void Next() ; virtual bool IsDone() const ; virtual void CurrentItem() const ; private: const List * _list; long _current; }; 8/40 NEXTPREV

LISTITERATOR //implementation template void ListIterator ::First() {_current = 0;} template void ListIterator ::Next() {_current++;} template bool ListIterator ::IsDone() {return _current >= _list->Count();} 9/40 NEXTPREV

LISTITERATOR //implementation template void ListIterator ::CurrentItem() const { if ( IsDone() ) { throw IteratorOutOfBounds }; return _list -> Get(_current); } 10/40 NEXTPREV

INDEPENDENT 11/40 NEXTPREV

ABSTRACTLIST //interface template class AbstractList { public: virtual Iterator * CreateIterator const = 0; //... }; 12/40 NEXTPREV

LIST //implementation template Iterator * List :: CreateIterator () const { return new ListIterator (this); }; 13/40 NEXTPREV

main int main () { AbstractList * employees //... Iterator * iterator = employees -> CreateIterator(); //... return 0; }; 14/40 NEXTPREV

main int main () { AbstractList * employees //... Iterator * iterator = employees -> CreateIterator(); delete iteraror; return 0; }; 15/40 NEXTPREV

ITERATORPTR //implementation template class IteratorPtr { public: IteratorPtr( Iterator * i): _i(i){}; ~IteratorPtr( delete _i); Iterator * operator -> () { return _i}; Iterator & operator * () { return * _i}; private: Iterator * _i; IteratorPtr(const IteratorPtr&) IteratorPtr& operator = (const IteratorPtr&) }; 16/40 NEXTPREV

main //implementation int main () { AbstractList * employees //... IteratorPtr * iterator = employees -> CreateIterator(); //... delete iteraror; return 0; }; 17/40 NEXTPREV

INDEPENDENT 18/40 NEXTPREV

INDEPENDENT 19/40 NEXTPREV

LISTTRAVERSER //interface template class ListTraverser { public: ListTraverser(List * aList); bool Traverse(); protected: virtual bool PorcessItem(const Item&) = 0; private: ListIterator _iterator; }; 21/40 NEXTPREV

LISTTRAVERSER //implementation template ListTraverse :: ListTraverser(List * aList ): _iterator(aList) {}; template bool ListTraverser :: Traverse() { bool result = false; for (!_iterator.First();!_iterator.IsDone(); _iterator.Next()) – { – result = PorcessItem(_iterator.CurrentItem()); – if (result == false) { break}; – } return result; } 21/40 NEXTPREV

PRINTNEMPLOEES //interface class PrintNEmploees : public ListTraverser { public: PrintNEmploees(List * aList, int n): ListTraverser (aList), _total(n),_count(0) (); protected: bool PorcessItem (Employee* const&); private: int _total; int _count; }; 22/40 NEXTPREV

PRINTNEMPLOEES //implementation bool PrintNEmploees::PorcessItem(Employee* const& e) { _count++; e->Print(); return _count < _total; } 23/40 NEXTPREV

main int main() { List * employees; PrintNEmploees pa (employees,10); pa.Traverse; //OR ListIterator iterator (employees); count = 0; for (iterator.First();!iterator.IsDone(); iterator.Next()) { count++; iterator.CurrentItem()-> Print(); if (count>=10)) { break}; } return 0; } 24/40 NEXTPREV

ITERATOR(JAVA) public class ArrayList extends AbstractList { private int size; // … some metods public Iterator iterator() { return new Itr(); } private class Itr implements Iterator {} 25/40 NEXTPREV

ITERATOR(JAVA) private class Itr implements Iterator { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount; public boolean hasNext() { return cursor != size; } … 26/40 NEXTPREV

ITERATOR(JAVA) public E next(){ int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } // … } 27/40 NEXTPREV

PROBLEM for (A a : arrayListA) { // do something for (B b : arrayListB) { // do something for (C c : arrayListC) { // do something } 28/40 NEXTPREV

PROBLEM for (Iterator i = arrayListA.iterator(); i.hasNext();) { a = i.next(); } public Iterator iterator() { return new Itr(); } 29/40 NEXTPREV

PROBLEM for (A a : arrayListA) { // 100 обєктів for (B b : arrayListB) { // 100 * 100 обєктів for (C c : arrayListC) { // 100 * 100* 100 обєктів } 30/40 NEXTPREV

PROBLEM for (Iterator i = arrayListA.iterator(); i.hasNext();) { a = i.next(); } public Iterator iterator() { return new Itr(); } 31/40 NEXTPREV

PROBLEM for (int i = 0; i < arrayListA.size(); i++) { A a = arrayListA.get(i); } 32/40 NEXTPREV

MORE QUESTION Алгоритм обходу Привілеї Стійкість Додаткові операції 33/40 NEXTPREV

TRAVERSALITY Алгоритм обходу не обов'язково знаходиться власне у ітераторі Cursor Але.. 34/40 NEXTPREV

FRIENDLY С++ надає можливість надати привілейований доступ до атрибутів і це той випадок, коли актуально. 35/40 NEXTPREV

ROBUST Проблема зміни і додання Гарантія стійкості 36/40 NEXTPREV

MORE OPERATION Previous Skip To … 37/40 NEXTPREV

CONCLUSIONS Викоритсовувти ітератори по можливості 38/40 NEXTPREV

GRATITUDE Thank you for your attention! 39/40 NEXTPREV

REFERENCES Эрих Гамма, Ричард Хелм, Ральф Джонсон, Джон Влиссидс. Приёмы объектно- ориентированного проектирования. Паттерны проектирования. /6-b14/java/util/ArrayList.java#ArrayList /6-b14/java/util/ArrayList.java#ArrayList 40/40 ENDPREV