CS 635: Advanced Object-Oriented Design & Programming |
---|
References | slide # 1 |
Bridge | slide # 2 |
...Applicability | slide # 4 |
...Bridge and Other Patterns | slide # 12 |
Advanced C++: Programming Styles and Idioms, James
Coplien, 1992, pp 58-72
This allows the implementation to vary from its abstraction
The abstraction defines and implements the interface
All operations in the abstraction call method(s) its implementation object
In client code:
Abstraction widget = new ConcreteImplA(); widget.operation();
We can vary the implementation!
Abstraction widget = new ConcreteImplA(); widget.operation();
((ConcreteImplA) widget).concreteOperation();
peer = implementation
public synchronized void setCursor(Cursor cursor) { this.cursor = cursor; ComponentPeer peer = this.peer; if (peer != null) { peer.setCursor(cursor); } }Abstractions & Imps independently subclassable
Methods in IconWindow and DialogWindow need to use the implementation methods to provide the new/modified functionality
This means that the WindowImp interface must provide the base functionality for window implementation
This does not mean that WindowImp interface must explicitly
provide an iconifyWindow method
String a( "cat"); String b( "dog"); String c( "mouse"); | |
a = b; | |
a = c; |
class StringRep { friend String; private: char *text; int refCount; StringRep() { *(text = new char[1] = '\0'; } StringRep( const StringRep& s ) { ::strcpy( text = new char[::strlen(s.text) + 1, s.text); } StringRep( const char *s) { ::strcpy( text = new char[::strlen(s) + 1, s); } StringRep( char** const *r) { text = *r; *r = 0; refCount = 1;; } ~StringRep() { delete[] text; } int length() const { return ::strlen( text ); } void print() const { ::printf("%s\n", text ); } }
class String { friend StringRep public: String operator+(const String& add) const { return *imp + add; } StringRep* operator->() const { return imp; } String() { (imp = new StringRep()) -> refCount = 1; } String(const char* charStr) { (imp = new StringRep(charStr)) -> refCount = 1; } String operater=( const String& q) { (imp->refCount)--; if (imp->refCount <= 0 && imp != q.imp ) delete imp; imp = q.imp; (imp->refCount)++; return *this; } ~String() { (imp->refCount)--; if (imp->refCount <= 0 ) delete imp; } private: String(char** r) {imp = new StringRep(r);} StringRep *imp; };
int main() { String a( "abcd"); String b( "efgh"); printf( "a is "); a->print(); printf( "b is "); b->print(); printf( "length of b is %d\n", b-<length() ); printf( " a + b "); (a+b)->print(); }
Strategy ?