November 14, 2019

An example of using Smalltalk collections

 

The Quad gallery gives solo exhibitions to some of its artists. A collection is needed to record all the works of art being exhibited. An exhibition may consist of any number of different types of work. When planning the show, some months prior to its opening, it is not known how many works will be exhibited. The gallery often have no accurate idea of what will be sent in by the artist. Several days are spent hanging the show and the final decision of what is to be included will often be finalised at the last possible moment. Consequently this collection will not be fixed in size. Cordelia visits the artists studio on several occasions in the months leading up to the show. If she says a painting is in, it's in, unless of course she sells it from the studio prior to the opening of the show. Additions and deletions will be necessary.

All of the works have been modelled with Smalltalk and are to be held in an ordered collection object referenced by exhibitionCollection. This will contain references to instances of the classes Painting and Drawing that you have seen earlier.

The following code illustrates how this is implemented.

painting1 := Painting new.
painting1 title: 'Goddess';
          yearCreated: '1999';
          height: 189;
          width: 155;
          media: 'Oil on cotton duck';
          price: 8000

drawing1 := Drawing new.
drawing1 title: 'Study of Rita';
         yearCreated: '2000';
         height: 64;
         width: 56;
         media: 'Charcoal and ink';
         price: 950

exhibitionCollection := OrderedCollection new.
exhibitionCollection add: painting1;
                     add: painting2;
                     add: painting3;
                     add: painting4; "And so on, adding paintings"
                     add: drawing1   "And so on, adding drawings"

Cordelia anticipates a sellout show and wishes to make an estimate of the total revenue.

|totalRevenue |
totalRevenue := 0.
exhibitionCollection do: [:element | totalRevenue := totalRevenue + element price].
^totalRevenue

This example illustrates two points.

  • An ordered collection can contain objects of any class, but it can be most useful when containing objects with a common abstract class.
  • By creating a price method in the abstract class Artwork, all the concrete subclasses will inherit the price message. The do: message can then be used to loop through all the elements to access their price. This is an example of inheritance being put to use.

Next page » SortedCollection

Previous page « The protocol of OrderedCollection

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Up to top of page