1/4
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Why
creating objects from scratch may be undesirable, especially if there is little difference between newly created objects
What
An object that clone() is used on returns a pointer to the prototype copy. Now new objects are made with the prototype as a starting point
abstract prototype (prototype interface) - allows client to abstract from prototype details
clone() is virtual, implemented in derived classes. May return covariant type
clone() is needed instead of copy constructor because constructor overriding is not real
different from factory. Factory creates objects from nothing, prototype just copies
Scoped Enumeration
unscoped enums are untyped and unscoped (global). if “class” is used after enum, it is now scoped and typed
Type Covariance
mechanism that enables overriding virtual function of derived class that accepts or returns type of derived class (only valid for pointers, references). Allows derived class ot have richer interface.
Code (Prototype Figures w covariance)
// base class
class Figure{
public:
Figure(int size): size_(size){}
void resize(int newSize){size_=newSize;}
// method required for prototype pattern
virtual Figure* clone() =0;
virtual void draw() =0;
virtual ~Figure(){}
protected:
int size_;
};
enum class Direction {Horizontal, Vertical};
class Line: public Figure{
public:
Line(int size, Direction dir):
dir_(dir), Figure(size){}
// clone returns base class pointer type
// Figure* clone() override {return new Line(size_, dir_);}
// clone returns covariant type
Line* clone() override {return new Line(size_, dir_);}
// flip changes direction of the line
// note, only lines can flip, not figures
void flip(){
dir_= dir_ == Direction::Horizontal ?
Direction::Vertical:
Direction::Horizontal;
}
void draw(){
for(int i=0; i<size_; ++i){
cout << '*';
if(dir_ == Direction::Vertical) cout << endl;
}
if(dir_ == Direction::Horizontal) cout << endl;
}
protected:
Direction dir_;
};
int main(){
// declares prototype line
Line prototypeLine(27, Direction::Horizontal);
// vector <Figure*> figures;
vector <Line*> figures;
for(int i=0; i<5; ++i)
figures.push_back(prototypeLine.clone());
// flip every other one
for(int i=0; i<5; ++i) {
// use method available for lines only
if(i % 2 == 0)
figures[i] -> flip();
}
// draw figures
for(int i=0; i<5; ++i) figures[i]->draw();
}