Design Patterns/Creational Patterns

Prototype Pattern (C++)

개발새발 2019. 9. 13. 21:20
반응형

Prototype Pattern (C++)

목적

현재 객체를 복사하여 (속성값이 동일한 또는 거의 유사한)새로운 객체를 생성한다.

java에서 clonnable 인터페이스(아래의 prototype class)와 동일하다. clone함수를 구현할 때 얕은 복사를 주의해야한다.

 

 

 

사용 시나리오

  • 포토샵이나 ppt에서 도형을 복사하는 시나리오가 있다.
  • 각각의 도형은 현재 도형의 바로 옆(x축으로 +1만큼 이동)에 생성 된다.

 

[Prototype]

class ShapePrototype {
public:
    virtual ShapePrototype* clone() = 0;
};

 

[ConcretePrototype]

class Circle : public ShapePrototype {
public:
    Circle(int x, int y, int r) {
        this->x = x;
        this->y = y;
        this->r = r;
    }
    virtual ShapePrototype* clone() override final {
        return new Circle(x+1, y, r);//x축으로 1만큼 이동
    }
    int getX() {
        return x;
    }
    int getY() {
        return y;
    }
private:
    int x;
    int y;
    int r;
};

 

[사용 예 Client]

int main(int argc, const char * argv[]) {
    ShapePrototype* circleA = new Circle(10, 20, 3);
    ShapePrototype* circleB = (Circle*)circleA->clone();
    
    printf("circleA address : %p \ncircleB address : %p\n\n", circleA, circleB);
    
    printf("A(%d, %d) B(%d, %d)\n", ((Circle*)circleA)->getX(), ((Circle*)circleA)->getY(), ((Circle*)circleB)->getX(),((Circle*)circleB)->getY());
    
    return 0;
}

 

실행 결과

circleA address : 0x1020317d0 

circleB address : 0x102031df0

 

A(10, 20) B(11, 20)

 

반응형