0% found this document useful (0 votes)
5 views3 pages

Lab 01

This document outlines the objectives and tasks for Lab #01 in the COSC301 Data Structures course at Ahmadu Bello University, focusing on design patterns such as Container, Iterator, and Visitor. It includes instructions for downloading necessary files, examples of design pattern implementations, and specific tasks for students to complete, including creating visitor classes and test applications. The lab aims to enhance understanding of design patterns through practical coding exercises.

Uploaded by

michaelugo796
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Lab 01

This document outlines the objectives and tasks for Lab #01 in the COSC301 Data Structures course at Ahmadu Bello University, focusing on design patterns such as Container, Iterator, and Visitor. It includes instructions for downloading necessary files, examples of design pattern implementations, and specific tasks for students to complete, including creating visitor classes and test applications. The lab aims to enhance understanding of design patterns through practical coding exercises.

Uploaded by

michaelugo796
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

DEPARTMENT OF MATHEMATICS, AHMADU BELLO UNIVERSITY

COSC301 : DATA STRUCTURES


LAB #01: Introduction to Design Patterns

Objectives:
To gain experience with:
 The Container Design Pattern
 The Iterator Design Pattern
 The Visitor Design Pattern

1. Downloads and Review:


Download the file [Link] from the lab document section of WebCT into your z-drive
and unzip it. After unzipping the file, a folder cosc301 will automatically be created with the
following files, most of which were discussed in lectures 3 and 4.
 [Link]
 [Link]
 [Link]
 [Link]
 [Link]
 [Link]
 [Link]
The code in these files should be understood from the lectures. Open each of these
files and review them to make sure you are familiar with what each of them does.
The rest of the lab (and indeed the rest of the course) depends very much these files.

2. Examples of Container, Visitor and Iterator design patterns:

You would notice that in addition to the above files, the unzipping program also
created a sub-folder, lab01 under the cosc301 main folder and stored a number of
files there. These are examples of concrete implementations of Container, Visitor and
Iterator design patterns and how to use them.

Example 1: The class MyContainer is a concrete class that extends the


AbstractContainer class. It stores its data using a Comparable array. Notice that
since array size is fixed, we need to override the isFull() method inherited from the
AbstractContainer class. Notice also that since we are not interested in comparing
two MyContainer containers, we are simply throwing MethodNotImplemented
exception in the implementation of the compareTo method.

The test class, TestMyContainer creates an instance of MyContainer and adds ten
Integer objects into it. It then makes use of the toString() method inherited from the
AbstractContainer class to print the contents of the container.

Example 2: The classes [Link] and [Link] show an


implementation and use of a visitor.
Example 3: The class [Link] shows how the elements in a container can
be processed using an Iterator.

Example 4: The class [Link] is another implementation of a visitor


showing that a visitor could have additional methods and instance variables if
necessary. The class TestAdditionVisitor shows how the AdditionVisitor may be
used.

Example 5: The class TestAdditionIterator shows how the elements of a container


may be summed up using an Iterator object.
Example 6: The visit method of any visitor does not have a loop to iterate the objects
of the visited container; this loop is in the accept method of the container. However, if
one or more instance variables of an object of the visited container is a container or a
data structure such as an array or a linked list, then the visit method may contain a
loop or loops to iterate the objects of the instance variable(s). The given Student
class contains a one-dimensional array instance variable qzGrade. The visit method
of StudentVisitor has a loop that iterates the elements of this array for each passed
Student object. The class TestStudentVisitor shows how the StudentVisitor may be
used.

3. Task #1
(a) Implement a visitor class SpecialVisitor, in the cosc301.lab01 package, that has
a constructor with the header: public SpecialVisitor(Comparable target, int n).
The visitor can be used to determine whether or not a MyContainer instance has
at least n target objects. Your visitor must be efficient; it must stop visiting the
container immediately it determines there are at least n target objects in the
container.
Note:
 All instance variables in SpecialVisitor must be private.
 Your SpecialVisitor must have a public boolean method
hasAtLeastNobjects to return the result of the search.
 Your SpecialVisitor must be general. That is, it must work with a
MyContainer containing any set of Comparable objects.

(b) Write an application, TestSpecialVisitor, in the cosc301.lab01 package, that


creates an instance of MyContainer, reads 12 integer values from the user and
inserts them, as Integer objects, into the container. Your application should then
prompt for an integer target, and an integer n. It should then:
(i) determine whether or not the container contains at least n Integer target
objects by using
a SpecialVisitor instance and by displaying an appropriate message.
(ii) print all the contents of the container using an Iterator object.

4. Task #2
(a) Implement a visitor class MaxMinVisitor, in the cosc301.lab01 package, that
can be used to find the maximum and the minimum elements in a container of
Comparable objects. The MaxMinVisitor should have two additional methods,
getMax( ) and getMin( ) that can be called after the visitor is done with its visit, to
get the maximum value and the minimum values respectively. NOTE: Your
MaxMinVisitor must be general. That is, it must work with a MyContainer
containing any set of Comparable objects. Also all instance variables in
MaxMinVisitor must be private.

(b) Write a test program TestMaxMinVisitor, in the cosc301.lab01 package, that


adds some Double objects into an instance of MyContainer and then it uses the
MaxMinVisitor to print the maximum and minimum elements of the container.

5. Task #3
Save the file, [Link] as [Link] and modify it
such that instead of using PrintingVisitor, it creates an anonymous inner class that
does exactly the same job as the PrintingVisitor and then use it to print the contents
of the container.

Common questions

Powered by AI

Design patterns such as Container, Iterator, and Visitor facilitate managing increasing complexity by providing structured yet flexible ways to interact with object collections. The Container pattern encapsulates storage management details, allowing developers to focus on content rather than structure . The Iterator pattern offers a uniform method to traverse containers, abstracting access sequences regardless of underlying implementation . Meanwhile, the Visitor pattern enhances flexibility by decoupling operations from the objects they work on, promoting extension and separation of concerns . Collectively, these patterns uphold modular, scalable solutions critical in handling experimental software complexity, ensuring adaptability as system requirements grow.

The creation of the TestSpecialVisitor application serves two critical roles: validation of the SpecialVisitor's proper operation and bridging user inputs with back-end data management. It ensures the visitor's logic detects whether at least 'n' target objects exist in the container, affirming its efficiency in stopping upon achieving the target count . By prompting user inputs and applying its result via SpecialVisitor, it links user interaction seamlessly to underlying data structures, validating both operational logic and user-system interface coherence, confirming practical usability and system reliability in real-world scenarios.

Using an anonymous inner class in place of a named visitor like TestPrintingVisitor can enhance flexibility by allowing for quick, specialized implementations without creating separate classes . However, it potentially impairs code maintainability due to the obscurity introduced by unnamed components, making the code harder to read and understand by other developers or even the original programmer over time . While it facilitates localized modifications and quick adaptations, it sacrifices the clarity and reusability that named classes offer. Thus, such a choice must balance immediate gains in flexibility against long-term code management challenges.

The SpecialVisitor class in the cosc301.lab01 package uses an iteration mechanism to traverse the MyContainer elements. It checks for the presence of at least n target objects by incrementing a counter each time a target match is found. The visitor stops further checks as soon as the counter reaches 'n', ensuring efficient use of resources . The result of whether the required number of target objects is present is provided by the 'hasAtLeastNobjects' method, which returns a boolean .

To adapt the visit method for nested collections or linked data structures, the method can integrate additional loops within its logic to navigate through each nested layer, executing specific operations corresponding to the visitor's purpose. As demonstrated by complex visitor implementations like the StudentVisitor, handling an array within a single object requires contextual loop embedding . By recursively or iteratively integrating nested loops, a visitor can traverse and apply logic across theoretically unlimited hierarchical structures, enabling deep, precise data interaction without altering base container class functionality, thus offering robust, scalable solutions across intricate data ecosystems.

The structure of MyContainer, which uses a fixed-size array to store Comparable objects, requires specific method adjustments. The `isFull` method, for instance, must be overridden to account for the container's static size, directly tying its logic to the array's capacity . As for `compareTo`, since MyContainer does not engage in container comparisons, the method is intentionally left unimplemented, throwing a MethodNotImplemented exception instead . This dynamic emphasizes the container's limitation scope, influencing method implementations to reflect underlying constraints and intended functionality.

In complex data structures with nested containers or dynamic arrays, a visitor can incorporate loops to handle inner structures. The StudentVisitor example illustrates this by accessing the qzGrade array, a member of the Student class, thus enabling piecewise operations on each Student object's properties beyond typical single-level interactions . This structure can be extended by adding methods in the visitor class to iterate through each nested element, fully utilizing container complexity and extending interaction capacity with nested data. Such scalability allows for comprehensive manipulation and inspection of multi-dimensional data within a program.

The Visitor design pattern allows an external class called a 'visitor' to operate on elements within a container without changing the container's structure. It is useful for performing new operations while keeping the container stable . In contrast, the Iterator design pattern provides a way to access elements sequentially without exposing the internal structure of the container. It creates an abstract interface to traverse through the collection . While visitors apply functions and gather data across various data structures, iterators strictly handle element sequences, emphasizing their respective operational and access roles.

The MethodNotImplemented exception is employed as a means to denote methods that are intentionally left without implementation within design patterns like COSC301, particularly when extending abstract classes that demand certain methods to be defined abstractly. For instance, when a class like MyContainer inherits from AbstractContainer but has no need to compare instances, defining 'compareTo' to throw this exception highlights areas deliberately unsupported to maintain pattern integrity . This approach enforces interface completeness while clearly communicating intentional non-implementation, safeguarding the system against unintended usage at runtime.

When implementing the MaxMinVisitor class, it is crucial to ensure that it accommodates any Comparable object. This means enhancing it to separately discern maximum and minimum through the 'getMax()' and 'getMin()' methods after processing a collection . Since visitors can operate across diverse Comparable data types, the class must handle object comparisons gracefully, respecting inherent type sorting without assuming specific data characteristics. Furthermore, maintaining instance variables as private ensures encapsulation, enhancing security and integrity when visitors interact with heterogeneous datasets . These considerations ensure versatility and correctness in retrieving extremal values.

You might also like