'Developer/Design Patterns'에 해당되는 글 27건

  1. 2014.05.17 Factory Pattern을 이용한 도형 만들기

// 객체를 생산하는 패턴 - 팩토리 패턴

// 파워포인트같은 도형 편집기

 

#include <iostream>

#include <vector>

using namespace std;

 

class Shape {

public:

        //자식의 공통의 인터페이스는 반드시 부모가 제공 해야한다.

        virtual void draw() = 0;

        virtual Shape* clone() = 0;

};

 

class Rect : public Shape {

       

public:

        void draw() { cout << "drawing Rect " << endl;}

        Shape* clone() { return new Rect(*this); }                  

};

 

class Circle : public Shape {

 

public:

        void draw() { cout << "drawing Circle " << endl;}

        Shape* clone() { return new Circle(*this); }        

};

 

class Triagle : public Shape {

public:

        void draw() { cout << "drawing Triagle " << endl;}

        Shape* clone() { return new Triagle(*this); }               

};

 

class ShapeFactory {

public:

        Shape* create(int typecode) {

               switch(typecode) {

               case 1:        return new Rect;

               case 2:        return new Circle;

               case 3:        return new Triagle;

               }

        }

};

 

int main(void) {

        vector<Shape*> v;

        ShapeFactory factory;

 

        while(1) {

               int cmd;               //1. 사각형, 2. , 0. 출력

               cin >> cmd;

 

               if(cmd < 0 ) continue;

               if(cmd == 0) {

                       for(int i=0; i < v.size(); i++) {

                              v[i]->draw();          //다형성(polymophidm)

                       }

                       continue;

               }

 

               if(cmd==9) {

                       cout << "# 도형을 복사 할까요 : ";

                       int num; cin >> num;

 

                       v.push_back(v[num-1]->clone());

               }

 

               v.push_back(factory.create(cmd));

              

        }

        return 0;

}

Posted by No names
,