Lecture 02 - Design Patterns
Lecture 02 - Design Patterns
Lecture 02 - Design Patterns
Lecture # 02:
Introduction
to
Design Patterns
9
The Container Pattern
• The first four methods are obvious. We explain the other two after
introducing Visitor and Iterator patterns.
10
The AbstractContainer Class
• The following is the AbstractContainer class, that implements the Container
interface and which will be used as a base from which concrete container
classes are derived.
public abstract class AbstractContainer
implements Container {
protected int count;
12
The Visitor Pattern (Contd.)
• The design framework for the accept method is as follows:
public class SomeContainer implements Container {
public void accept(Visitor visitor) {
for each object, o, in this container
visitor.visit(o);
}
}
14
The AbstractVisitor Class
15
The toString Method
• The following defines the toString method for the AbstractContainer
class using a visitor.
• Defining it here is aimed at simplifying the implementation of classes
extending this class.
• While the accept method takes only one visitor, a container can 17
have more than one Iterator at the same time.
The accept Method
• We now define the accept method for the AbstractContainer class using
an iterator.
18
The SearchableContainer Pattern
• Some of the data structures we shall study have the additional property of
being searchable.
• The SearchableContainer interface extends the Container interface by
adding four more methods as shown below:
19
The Association Pattern
• An association is an ordered pair of objects.
• The first element is called the key, while the second is the value associated
with the key.
• The following defines the Association class which we shall use whenever we
need to associate one object to another.
interface Container {
public Iterator getIterator();
}
@Override
public Iterator getIterator() {
return new CollectionofNamesIterate() ;
}
22
…Cont
private class CollectionofNamesIterate implements Iterator{
int i;
@Override
public boolean hasNext() {
if (i<name.length){
return true;
}
return false;
}
@Override
public Object next() {
if(this.hasNext()){
return name[i++];
}
return null;
}
}
}
23
…Cont
public class IteratorPatternDemo {
24
Review Questions
Sources:
•https://howtodoinjava.com/gang-of-four-java-design-patterns/
•https://www.javatpoint.com/iterator-pattern 25