Reputation: 871
I want to check if the examples below (from a test interview) corresponds to the correct design pattern name :
Example 1 : can that piece of code illustrate the "Builder" pattern or it might be the "Strategy" one ?
FileStream* files = new FileStream("my_file.zip");
BufferedStream* bufferds = new BufferedStream(files);
ZipStream* zips = new ZipStream(bufferds);
Example 2 : is the code below represent the "Strategy" pattern ?
struct UnixText {
void write(string str) { cout << str; }
void lf() { cout << "\n"; }
};
struct WindowsText {
void write(string str) { cout << str; }
void crlf() { cout << "\r\n"; }
};
struct Writer {
virtual void write(string str) = 0;
virtual void newline() = 0;
virtual ~Writer() {}
};
struct UnixWriter : Writer {
UnixWriter(UnixText* tx) { _target = tx; }
virtual void write(string str) { _target->write(str); }
virtual void newline() { _target->lf(); }
private:
UnixText* _target;
};
struct WindowsWriter : Writer {
WindowsWriter(WindowsText* tx) { _target = tx; }
virtual void write(string str) { _target->write(str); }
virtual void newline() { _target->crlf(); }
private:
WindowsText* _target;
};
int main()
{
Writer* writer = (g_IsUnix) ? (Writer*) new UnixWriter(new UnixText()) : (Writer*) new WindowsWriter(new WindowsText());
writer->write("Hello");
writer->newline();
writer->write("World");
}
Upvotes: 1
Views: 770
Reputation: 21124
The first example uses I/O streams and it is a good use of Decorator
pattern. Here it has a constructor that takes an instance of the same abstract class or interface. That's the recognition key of the Decorator
pattern
The second one, you are passing some Writing Strategy
to the UnixWriter
and WindowsWriter
which is the context. So it can be considered as Strategy
pattern. But you can still improve it by having a contract for Writing Strategy. So your concrete writers should only know about that super type rather than having references to concrete implementations. That will make your system more flexible.
Upvotes: 1