Programming/Design Patterns

Iterator Design Pattern

jasu 2007. 2. 21. 10:54
// Iterator interface //

interface Iterator{
        public function hasNext():Boolean;
        public function next():Object;
}

// Aggregate interface //

interface Aggregate{
        public function iterator():Iterator;
}

// Book class //

class Book{
        private var name:String = "";
        public function Book(name:String){
                this.name = name;
        }
        public function getName():String{
                return name;
        }
}


// BookShelfIterator class //

class BookShelfIterator implements Iterator{
        private var bookShelf:BookShelf;
        private var index:Number;
        private var book:Book;
        public function BookShelfIterator(bookShelf:BookShelf){
                this.bookShelf = bookShelf;
                this.index = 0;
        }
        public function hasNext():Boolean{
                if(this.index < bookShelf.getLength()){
                        return true;
                }else{
                        return false;
                }
        }
        public function next():Object{
                this.book = bookShelf.getBookAt(this.index);
                this.index++;
                return this.book;
        }
}



// BookShelf class//



class BookShelf implements Aggregate{
        private var books:Array;
        private var last:Number = 0;
        public function BookShelf(){
                this.books = new Array();
        }
        public function getBookAt(index:Number):Book{
                return books[index];
        }
        public function appendBook(book:Book):Void{
                this.books[last] = book;
                last++;
        }
        public function getLength():Number{
                return last;
        }
        public function iterator():Iterator{
                return new BookShelfIterator(this);
        }
}



// Main class //

class Main{
        private var bookShelf:BookShelf;
        private var it:Iterator;
        private var book:Book;
        public function Main(){
                init();
        }
        public function init(){
                this.bookShelf = new BookShelf();
                this.bookShelf.appendBook(new Book("Around the World in 80 Days"));
                this.bookShelf.appendBook(new Book("Bible"));
                this.bookShelf.appendBook(new Book("Cinderella"));
                this.bookShelf.appendBook(new Book("Daddy-Long-Legs"));
                this.it = bookShelf.iterator();
                while(it.hasNext()){
                        this.book = Book(it.next());
                        trace(""+this.book.getName());
                }
        }
}