sliver__

Design Pattern(2) 본문

CS/디자인패턴

Design Pattern(2)

sliver__ 2021. 11. 22. 22:08
728x90

[Abstract Data Type (ADT)]

- 데이터와 관계된 기능을 한가지 의미적인 요소로 캡슐화

 

Single syntatic unit

Encapsulation

 

[Class = ADT + Inheritance + Polymorphsim (=> reusability + flexibilit y)]

- 클라이언트 코드에서 변경되지 않고 재사용 될 수 있는지에 초점

 

[Inheritance]

Ex) Y가 X를 상속받은 경우 

=> Y는 X의 함수, 데이터를 상속받는다

=> Y is X

 

[Polymorphism]

- 다른 클래스의 같은 이름의 opreation이 존재할 때, 다른 방식으로 동작가능

- Conditional state를 크게 감소

 

Runtime polymorphsim (Dynamic Polymorphsim)

- Method Overriding

 

Compile time polymorphsim (Static Polymorphsim)

- Method Overloading

 

Ex) Method Overloading

class X
{
	public:
    	void methodA(int num){}
        void methodA(int num1, int num2){}
        void methodA(double num)
};

=> Compile time에 결정

 

Ex) Method Overriding

class X
{
	public:
    	void methodA(){cout << "class X" << endl;}
};

class Y : public class X
{
	public:
    	void methodA(){cout << "class Y" << endl;}
};

int main(void)
{
    X obj1 = new X();
    X obj2 = new Y();
    obj1.methodA();
    obj2.methodA();
}

obj1 result : class X

obj2 result : class Y

=> Runtime에 결정 (이유 : X의 객체가 X일지 Y일지 Runtime에 결정된다.)

- 변수도 마찬가지이다. Rumtime에 자신의 object일지 아니면 후손의 object 중 하나일 것이다.

- 반대로 후손일 경우 부모의 클래스로 생성할 수 없다. 당연히 왜냐하면 후손일 경우 더 많이 구현가능한데 부모 객체로 선언을 한다는 자체가 불가능

 

[Abstract Class and Abstract Method]

- Abstract Class의 경우 Instance를 만들 수 없다.

- Abstract Class를 상속받은 자손 Class에서 redefine해주고 후손 Class는 Instance 생성 가능하다.

- Abstract Class를 상속받은 자손은 부모의 객체 타입으로 생성될 수 있다

class Animal
{
	virtual void abstract say()=0;
};

class Cat : public Animal
{
...
};
Animal a = null;
Cat nabi = new Cat();

a = nabi;

- 반대로 자식의 포인터로 부모를 가리킬 수는 없다.

- 형제간에는 객체를 선언해서 생성할 수 없다.

 

[How a decision is made about which method to run]

1. 현재 reference된 객체를 method를 호출한다.

2. 만약 reference된 객체에 함수가 없다면 superclass의 method를 호출한다.

3. method가 없다면 error => 미리 compiler가 check

 

[Interface]

- 상위 class로 상속시킬 interface class를 만들어 하위 class에서 구현을 해서 사용하는 방식.

- JAVA의 implements로 interface class를 상속가능

 

[Abstract vs Interface]

- "is a" 관계일 때 Abstract를 쓰는게 맞다.

- 부분적으로 구현이 필요할 때

- 나머지 경우는 Interface를 사용하는것이 좋다.

 

=> 상위 class 일수록 하위의 class를 쓸 수 있는 범위가 더 늘어난다. (당연)

그러나 무조건 올라갈수록 좋은걸까?

method를 호출할 수 있는 범위가 줄어든다!

=> 상위 클래스에서 선언된 함수만 호출할 수 있기 때문이다.

그러므로 적절한 수준에서 상속을 멈춰야한다.

 

[Information Hiding]

- 자주 변하게 되는 지점을 interface로 선언하여 interface를 상속받은 class가 자주변하더라도 dependency가 있는  client는 변하지 않게 유지하는 설계구조를 따라야한다.

728x90

'CS > 디자인패턴' 카테고리의 다른 글

Design Pattern(3) - SOLID principles  (0) 2022.01.01
Design Pattern (1)  (0) 2021.11.18
Comments