对象设计中的多对多关系

时间:2011-02-09 18:22:18

标签: c# oop

我有类似的问题:

Many to many object to object relation in C#

但是,想象一下,锦标赛将有一个“最后播放日期”属性(仅作为示例)将映射到任何参与者。在这种情况下,该财产最终会在哪里?是否必须创建一个中级类? (我不想这样做)我有什么选择?谢谢!

1 个答案:

答案 0 :(得分:2)

一种方法是在每个包含指向其他对象的指针的数组上,通过将对象存储为键的字典和作为值存储的日期(或任意数量的属性的自定义属性类)或使用包装器在对象和普通列表周围,这个包装器应该实现装饰器模式,以允许直接访问对象以及任何唯一属性。

包装器对象可以使用内部对象作为2个不同对象的选择性包装器对象之间共享的属性,以便任何属性同步。

另一种方式是一个单独的对列表,其中一个像上面一样被包裹。

后者可以轻松遍历所有对象。

这是一个代码示例,它可能不是您需要的,但它可能会为您提供我的想法的基础知识。

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; }
    }   
}
相关问题