샌디는 무슬림으로 전환하여 파티마라는 새로운 이름을 사용하고 새로운 무슬림 속성 (예 : 종교 == 이슬람교 등)을 가진 Sandy의 모든 속성을 가진 Person 클래스입니다. . 이 시점에서 샌디는 삭제 될 수 있으며, 현재 이슬람 교실의 파티마 (Fatima)는 샌디 (Sandy)의 역할을 수행 할 것입니다. 문제는 새 주소로 인해 샌디가 파티마를 알지 못한다는 것을 아는 모든 사람들입니다. Sandy의 주소를 Fatima의 주소로 수동으로 변경하면 Sandy를 아는 모든 사람들이 분명히 받아 들일 수있는 방법이 아닙니다. 디자인을 개선하는 방법에 대한 제안?오브젝트를 다른 클래스로 변환
#include <iostream>
#include <string>
#include <typeinfo>
class Person {
std::string name;
Person* bestFriend;
public:
Person (const std::string& newName) : name (newName) {}
virtual ~Person() = default;
std::string getName() const {return name;}
void setName (const std::string& newName) {name = newName;}
Person* getBestFriend() const {return bestFriend;}
void setBestFriend (Person* newBestFriend) {bestFriend = newBestFriend;}
};
class Muslim: public Person {
public:
Muslim (const Person& person) : Person (person) {
// religion = Islam; etc...
}
};
int main() {
Person *mary = new Person ("Mary"), *sandy = new Person ("Sandy");
mary->setBestFriend (sandy);
std::cout << "sandy = " << sandy << ", " << typeid(*sandy).name() << std::endl;
std::cout << mary->getName() << "'s best friend is " << mary->getBestFriend()->
getName() << "." << std::endl;
Muslim* fatima = new Muslim (static_cast<Muslim>(*sandy)); // the big change
fatima->setName ("Fatima"); // should now delete sandy, because fatima takes on every attribue of sandy
std::cout << "fatima = " << fatima << ", " << typeid(*fatima).name() << std::endl;
std::cout << mary->getName() << "'s best friend is " << mary->getBestFriend()->
getName() << "." << std::endl; // still Sandy, of course
}
출력 :
모래 = 0x32658, 6 인
메리의 가장 친한 친구 샌디 여기에 문제를 보여주는 내 간단한 코드입니다. 0x23fec0
파티마 = 6Muslim
메리의 가장 친한 친구 샌디이다.
물론, 우리는 다음을 원합니다 : Mary의 가장 친한 친구는 mary-> getBestFriend() -> getReligion() == 이슬람교 등과 같은 파티마입니다. 모든 것을 재 설계하여 자동화되도록하는 방법 (그녀를 아는 사람들이 수천 명이 있다고 가정)?
클래스 무슬림은 Person 메소드 (및 많은 새로운 데이터 멤버 및 메소드)에 대해 여러 가지 복잡한 우선 순위를 갖기 때문에 상속을 사용하려고합니다.
상속은 여기에서 과도한 것처럼 보입니다. 왜 '사람'이라는 종교 회원 만있는 것이 아닌가? –
@Joseph Mansfield. 왜냐하면 클래스 무슬림은 Person 메소드에 대해 여러 가지 복잡한 우선 순위를 갖기 때문입니다. – prestokeys
@prestokeys 이런 경우에, 의존성 주사를 사용하여 종교에 기초한 다른 세트를 주입하지 마십시오 (상관 관계가 어떻게 작용하는지 가정) – DNT