这是我一直在努力寻找最佳解决方案的问题。我在使用 PHP 和 Java 时遇到了这个问题,所以这是对 OOP 问题的基本理解。示例在 PHP 中。
假设我在这里有一些对象。歌曲、艺术家、ArtistProfile、用户。
因此,在某些情况下,当我调用艺术家(例如艺术家的个人资料页面)时,我需要 ArtistProfile 和一组用户对象(订阅者),而在其他情况下,我只需要艺术家信息,例如查看歌曲页面时。
我应该将一个对象嵌套为另一个对象的一部分,还是应该为不同的用途创建更具体的对象。
选项 1:嵌套
Class Song {
private $songId;
private $songName;
private $year;
private $Artist; //Artist object
}
Class Artist {
private $artistId;
private $name;
private $age;
private $subscriberArr; //Array of User objects which then have more nested objects such as a Role object, Profile object
private $profile; //Profile object which could also have more nested objects
}
Class User {
private $userId;
private $name;
private $age;
private $role; //Role object
private $profile; //UserProfile object
}
选项 2:构建更多对象
Class Song {
private $songId;
private $songName;
private $year;
private $artistId;
}
Class Artist {
private $artistId;
private $age;
private $name;
}
Class User {
private $userId;
private $name;
private $age;
private $roleId;
}
Class SongWithArtist {
private $song; //Basic Song object
private $artist; //Basic Artist object
}
Class ArtistWithProfile {
private $artist; //Basic artist object
private $profile; //Profile object
private $subscriberArr; //UserDisplay object containing basic User object
}
Class UserWithProfile {}
选项 1 意味着浪费大量时间/资源来获取该页面可能不需要但更易于管理的信息。选项 2 很混乱,需要跟踪哪个对象是什么,但是更快且更少的 db 调用。哪个是“正确”选项和/或是否有第三个正确选项?