Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
B.Eckel - Thinking in C++, Vol.2, 2nd edition.pdf
Скачиваний:
50
Добавлен:
08.05.2013
Размер:
2.09 Mб
Скачать

Abstracting usage

With creation out of the way, it’s time to tackle the remainder of the design: where the classes are used. Since it’s the act of sorting into bins that’s particularly ugly and exposed, why not take that process and hide it inside a class? This is simple “complexity hiding,” the principle of “If you must do something ugly, at least localize the ugliness.” In an OOP language, the best place to hide complexity is inside a class. Here’s a first cut:

vector<Aluminum*>

TrashSorter vector<Paper*>

vector of

Trash bins

vector<Glass*>

vector<Cardboard*>

A TrashSorter object holds a vector that somehow connects to vectors holding specific types of Trash. The most convenient solution would be a vector<vector<Trash*>>, but it’s too early to tell if that would work out best.

In addition, we’d like to have a sort( ) function as part of the TrashSorter class. But, keeping in mind that the goal is easy addition of new types of Trash, how would the statically-coded sort( ) function deal with the fact that a new type has been added? To solve this, the type information must be removed from sort( ) so all it needs to do is call a generic function which takes care of the details of type. This, of course, is another way to describe a virtual function. So sort( ) will simply move through the vector of Trash bins and call a virtual function for each. I’ll call the function grab(Trash*), so the structure now looks like this:

 

vector<Aluminum*>

 

bool grab(Trash*);

TrashSorter

vector<Paper*>

 

bool grab(Trash*);

vector of

 

Trash bins

vector<Glass*>

 

 

bool grab(Trash*);

 

vector<Cardboard*>

 

bool grab(Trash*);

Chapter 16: Design Patterns

488

However, TrashSorter needs to call grab( ) polymorphically, through a common base class for all the vectors. This base class is very simple, since it only needs to establish the interface for the grab( ) function.

Now there’s a choice. Following the above diagram, you could put a vector of trash pointers as a member object of each subclassed Tbin. However, you will want to treat each Tbin as a vector, and perform all the vector operations on it. You could create a new interface and forward all those operations, but that produces work and potential bugs. The type we’re creating is really a Tbin and a vector, which suggests multiple inheritance. However, it turns out that’s not quite necessary, for the following reason.

Each time a new type is added to the system the programmer will have to go in and derive a new class for the vector that holds the new type of Trash, along with its grab( ) function. The code the programmer writes will actually be identical code except for the type it’s working with. That last phrase is the key to introduce a template, which will do all the work of adding a new type. Now the diagram looks more complicated, although the process of adding a new type to the system will be simple. Here, TrashBin can inherit from TBin, which inherits from vector<Trash*> like this (the multiple-lined arrows indicated template instantiation):

TBin : public vector<Trash*>

virtual bool grab(Trash*);

template TrashBin<TrashType> (implements grab();)

TrashSorter

vector of

TrashBins

bool sort(Trash*);

TrashBin<Paper>

TrashBin<Glass>

TrashBin<Aluminum>

TrashBin<Cardboard>

The reason TrashBin must be a template is so it can automatically generate the grab( ) function. A further templatization will allow the vectors to hold specific types.

That said, we can look at the whole program to see how all this is implemented.

//: C09:Recycle4.cpp //{L} TrashPrototypeInit

//{L} fillBin Trash TrashStatics

// Adding TrashBins and TrashSorters

Chapter 16: Design Patterns

489

#include "Trash.h" #include "Aluminum.h" #include "Paper.h" #include "Glass.h" #include "Cardboard.h" #include "fillBin.h" #include "sumValue.h" #include "../purge.h" #include <fstream> #include <vector> using namespace std;

ofstream out("Recycle4.out");

class TBin : public vector<Trash*> { public:

virtual bool grab(Trash*) = 0;

};

template<class TrashType> class TrashBin : public TBin { public:

bool grab(Trash* t) {

TrashType* tp = dynamic_cast<TrashType*>(t); if(!tp) return false; // Not grabbed push_back(tp);

return true; // Object grabbed

}

};

class TrashSorter : public vector<TBin*> { public:

bool sort(Trash* t) {

for(iterator it = begin(); it != end(); it++) if((*it)->grab(t))

return true; return false;

}

void sortBin(vector<Trash*>& bin) { vector<Trash*>::iterator it;

for(it = bin.begin(); it != bin.end(); it++) if(!sort(*it))

cerr << "bin not found" << endl;

}

~TrashSorter() { purge(*this); }

Chapter 16: Design Patterns

490

};

int main() { vector<Trash*> bin;

// Fill up the Trash bin: fillBin("Trash.dat", bin); TrashSorter tbins;

tbins.push_back(new TrashBin<Aluminum>); tbins.push_back(new TrashBin<Paper>); tbins.push_back(new TrashBin<Glass>); tbins.push_back(new TrashBin<Cardboard>); tbins.sortBin(bin);

for(TrashSorter::iterator it = tbins.begin(); it != tbins.end(); it++)

sumValue(**it);

sumValue(bin);

purge(bin); } ///:~

 

 

 

Tbins:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Aluminum Vector

 

 

 

 

 

 

 

 

 

 

 

 

 

boolean grab(Trash)

Trash Sorter

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Paper Vector

 

 

Vector of

 

 

 

 

 

 

 

 

 

 

 

boolean grab(Trash)

 

Trash Bins

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Glass Vector

 

 

 

 

 

 

 

 

 

 

 

 

 

boolean grab(Trash)

 

 

 

 

 

 

 

TrashSorter needs to call each grab( ) member function and get a different result depending on what type of Trash the current vector is holding. That is, each vector must be aware of the type it holds. This “awareness” is accomplished with a virtual function, the grab( ) function, which thus eliminates at least the outward appearance of the use of RTTI. The implementation of grab( ) does use RTTI, but it’s templatized so as long as you put a new TrashBin in the TrashSorter when you add a type, everything else is taken care of.

Memory is managed by denoting bin as the “master container,” the one responsible for cleanup. With this rule in place, calling purge( ) for bin cleans up all the Trash objects. In addition, TrashSorter assumes that it “owns” the pointers it holds, and cleans up all the TrashBin objects during destruction.

Chapter 16: Design Patterns

491

Соседние файлы в предмете Численные методы
  • #
    08.05.20133.99 Mб22A.Menezes, P.van Oorschot,S.Vanstone - HANDBOOK OF APPLIED CRYPTOGRAPHY.djvu
  • #
  • #
    08.05.20135.91 Mб24B.Eckel - Thinking in Java, 3rd edition (beta).pdf
  • #
  • #
    08.05.20136.09 Mб17D.MacKay - Information Theory, Inference, and Learning Algorithms.djvu
  • #
    08.05.20133.85 Mб15DIGITAL Visual Fortran ver.5.0 - Programmers Guide to Fortran.djvu
  • #
    08.05.20131.84 Mб12E.A.Lee, P.Varaiya - Structure and Interpretation of Signals and Systems.djvu