samedi 27 janvier 2018

identifying the design pattern name used

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");

}

Aucun commentaire:

Enregistrer un commentaire