- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
struct IText{
typedef boost::shared_ptr<IText> SPtr;
virtual void draw() = 0;
virtual void add(const SPtr&) {
throw std::runtime_error("IText: Can't add to a leaf");
}
virtual void remove(const SPtr&){
throw std::runtime_error("IText: Can't remove from a leaf");
}
};
struct CompositeText: public IText{
void add(const SPtr& sptr){
children_.push_back(sptr);
}
void remove(const SPtr& sptr){
children_.remove(sptr);
}
void replace(const SPtr& oldValue, const SPtr& newValue){
std::replace(children_.begin(), children_.end(), oldValue, newValue);
}
virtual void draw(){
BOOST_FOREACH(SPtr& sptr, children_){
sptr->draw();
}
}
private:
std::list<SPtr> children_;
};
struct Letter: public IText{
Letter(char c):c_(c) {}
virtual void draw(){
std::cout<<c_;
}
private:
char c_;
};
int main(){
CompositeText sentence;
IText::SPtr lSpace(new Letter(' '));
IText::SPtr lExcl(new Letter('!'));
IText::SPtr lComma(new Letter(','));
IText::SPtr lNewLine(new Letter('\n'));
IText::SPtr lH(new Letter('H')); // letter 'H'
IText::SPtr le(new Letter('e')); // letter 'e'
IText::SPtr ll(new Letter('l')); // letter 'l'
IText::SPtr lo(new Letter('o')); // letter 'o'
IText::SPtr lW(new Letter('W')); // letter 'W'
IText::SPtr lr(new Letter('r')); // letter 'r'
IText::SPtr ld(new Letter('d')); // letter 'd'
IText::SPtr li(new Letter('i')); // letter 'i'
IText::SPtr wHello(new CompositeText);
wHello->add(lH);
wHello->add(le);
wHello->add(ll);
wHello->add(ll);
wHello->add(lo);
IText::SPtr wWorld(new CompositeText); // word "World"
wWorld->add(lW);
wWorld->add(lo);
wWorld->add(lr);
wWorld->add(ll);
wWorld->add(ld);
sentence.add(wHello);
sentence.add(lComma);
sentence.add(lSpace);
sentence.add(wWorld);
sentence.add(lExcl);
sentence.add(lNewLine);
sentence.draw(); // ptrints "Hello, World!\n"
IText::SPtr wHi(new CompositeText); // word "Hi"
wHi->add(lH);
wHi->add(li);
sentence.replace(wHello, wHi);
sentence.draw(); // ptrints "Hi, World!\n"
sentence.remove(wWorld);
sentence.remove(lSpace);
sentence.remove(lComma);
sentence.draw(); // ptrints "Hi!\n"