nakka soft world !

객체 지향 디자인 본문

프로그래밍언어/C++

객체 지향 디자인

nakka 2017. 3. 27. 15:30
728x90

#include <iostream>

#include <vector>

using namespace sd;


// #1. 각도형을 타입으로 만들면 편리 하다.

class Rect

{

public:

void Draw() { cout << "Rect Draw"<< endl; }

};

class Circle

{

public:

void Draw() { cout << "Circle Draw"<< endl; }

};


int main()

{

vector<Rect*> v1;

vector<Circle*> v2;

}



// #2. 기반 클래스가 있다며 모든 파생 클래스를 같이 묶을 수 있다.

class Shape{};


class Rect : public Shape

{

public:

void Draw() { cout << "Rect Draw"<< endl; }

};

class Circle : public Shape

{

public:

void Draw() { cout << "Circle Draw"<< endl; }

};


int main()

{

vector<Shape*> v;

int cmd;

while(1)

{

cin >> cmd;

if (cmd == 1) v.push_back(new Rect);

else if (cmd == 2) v.push_back(new Circle);

else if (cmd == 9)

{

for (auto p : v)

p->Daw();   // error

}

}




// #3. 모든 도형의 공통의 특징은 반드시 기반 클래스인 Shape에도 있어야 한다.

class Shape {

public:

void Draw() { cout << "Shape Draw"<< endl; }

};


class Rect : public Shape

{

public:

void Draw() { cout << "Rect Draw"<< endl; }

};

class Circle : public Shape

{

public:

void Draw() { cout << "Circle Draw"<< endl; }

};


int main()

{

vector<Shape*> v;

int cmd;

while(1)

{

cin >> cmd;

if (cmd == 1) v.push_back(new Rect);

else if (cmd == 2) v.push_back(new Circle);

else if (cmd == 9)

{

for (auto p : v)

p->Draw();   // 모두 Shape을 그림

}

}




// #4. 파생 클래스가 재정의 하는 함수는 반드시 가상함수가 되어야 한다.


class Shape{

public:

virtual void Draw() { cout << "Shape Draw"<< endl; }

};


class Rect : public Shape

{

public:

virtual void Draw() { cout << "Rect Draw"<< endl; }

};

class Circle : public Shape

{

public:

virtual void Draw() { cout << "Circle Draw"<< endl; }

};

class Triangle : public Shape

{

public:

virtual void Draw() { cout << "Triangle Draw"<< endl; }

};


int main()

{

vector<Shape*> v;

int cmd;

while(1)

{

cin >> cmd;

if (cmd == 1) v.push_back(new Rect);

else if (cmd == 2) v.push_back(new Circle);

else if (cmd == 9)

{

for (auto p : v)

p->Draw();   // 객체에 따라 호출되는 함수가 다름. 다형성(polymorphism), 나중에 추가되는 객체에 따라 Code를 바꾸지 않아도 됨.

}

}

}


// OCP원칙

// 기능 확장에는 열려 있고, (Open)

// 코드 수정에는 닫혀 있어야 (Close)

// 하는 원칙 (Principle)

728x90

'프로그래밍언어 > C++' 카테고리의 다른 글

순수 가상 함수와 추상 클래스  (0) 2017.03.27
가상 소멸자 ( virtual destructor )  (0) 2017.03.27
가상함수와 다형성  (0) 2017.03.27
상속의 개념  (0) 2017.03.25
STL 설계 철학  (0) 2017.03.19
Comments