[英]Many to Many relationship in object design
我有類似的問題:
但是,想象一下錦標賽將具有一個“最后一次比賽”屬性(僅作為示例),該屬性將映射到任何參與者。 在這種情況下,該財產最終會在哪里? 是否必須創建一個中級類? (我不想這樣做)我有什么選擇? 謝謝!
一種方法是在每個對象上都有一個包含指向其他對象的指針的數組,方法是通過將對象存儲為鍵並將日期存儲為值的字典(或任意數量的屬性的自定義屬性類),或在對象周圍使用包裝器類對象和普通列表,然后這個包裝器應該實現裝飾器模式,以允許直接訪問對象以及任何唯一屬性。
包裝對象可以使用內部對象作為屬性,該屬性在兩個不同對象的相對包裝對象之間共享,以便任何屬性都是同步的。
另一種方法是像上面那樣包裝成對的單獨列表。
后者可以輕松遍歷所有對象。
這是一個代碼示例,它可能不是您需要的,但它可能會為您提供我的想法的基礎知識。
void Main()
{
var p = new Player("David");
var c = new Championship("Chess");
p.LinkChampionship(c, DateTime.Now);
p.Dump();
}
// Define other methods and classes here
class Player : Properties {
public virtual String Name {get; set;}
public List<ChampionshipWrapper> champs = new List<ChampionshipWrapper>();
public Player() {
}
public Player(string name) {
Name = name;
}
public void LinkChampionship(Championship champ, DateTime when) {
var p = new Properties(when);
champs.Add(new ChampionshipWrapper(champ, p));
champ.players.Add(new PlayerWrapper(this, p));
}
}
class Championship : Properties {
public virtual String Name { get; set; }
public List<PlayerWrapper> players = new List<PlayerWrapper>();
public Championship(){}
public Championship(string name) {
Name = name;
}
public void LinkPlayer(Player play, DateTime when) {
var p = new Properties(when);
players.Add(new PlayerWrapper(play, p));
play.champs.Add(new ChampionshipWrapper(this, p));
}
}
class Properties {
public virtual DateTime LastPlayed { get; set; }
public Properties() {
}
public Properties(DateTime when) {
LastPlayed = when;
}
}
class PlayerWrapper : Player {
private Player player;
private Properties props;
public PlayerWrapper(Player play, Properties prop) {
this.player = play;
this.props = prop;
}
public override String Name {
get { return this.player.Name; }
set { this.player.Name = value; }
}
public override DateTime LastPlayed {
get { return this.props.LastPlayed; }
set { this.props.LastPlayed = value; }
}
}
class ChampionshipWrapper : Championship {
private Championship champ;
private Properties props;
public ChampionshipWrapper(Championship c, Properties prop) {
this.champ = c;
this.props = prop;
}
public override String Name {
get { return this.champ.Name; }
set { this.champ.Name = value; }
}
public override DateTime LastPlayed {
get { return this.props.LastPlayed; }
set { this.props.LastPlayed = value; }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.