所以我想设计这样的团队/球员关系:每个球员都属于一个球队,但因为我想用界面练习,所以我制作了 ITeam 和 IAthlete,然后制作了 BasketballTeam 和 BasketballPlayer。然后我写了这段代码:
public interface IAthlete
{
string GetName();
string GetSport();
}
public interface ITeam
{
void AddPlayer(IAthlete player);
IAthlete[] GetAthletes();
string GetName();
int GetNumberOfPlayers();
}
public class BasketballPlayer:IAthlete
{
private string name;
public string GetName()
{
return this.name;
}
public string GetSport()
{
return "Basketball";
}
public BasketballPlayer(string name)
{
this.name = name;
}
public void Run(int distance)
{
Console.WriteLine(this.name + " just ran " + distance.ToString() + " meters.");
}
public bool Shoot()
{
Console.WriteLine("Successful shot for " + this.name);
return true;
}
}
public class BasketballTeam: ITeam
{
BasketballPlayer[] players;
int numberOfPlayers;
private string name;
public void AddPlayer(BasketballPlayer player)
{
this.players[this.numberOfPlayers] = player;
this.numberOfPlayers++;
}
public IAthlete[] GetAthletes()
{
return this.players;
}
public string GetName()
{
return this.name;
}
public int GetNumberOfPlayers()
{
return this.numberOfPlayers;
}
public BasketballTeam(string name)
{
this.numberOfPlayers = 0;
this.name = name;
this.players = new BasketballPlayer[10];
}
}
class Program
{
static void Main(string[] args)
{
BasketballTeam bt = new BasketballTeam("MyTeam");
BasketballPlayer bp = new BasketballPlayer("Bob");
bt.AddPlayer(bp);
foreach (BasketballPlayer player in bt.GetAthletes())
{
Console.WriteLine(player.GetName());
}
foreach (IAthlete a in bt.GetAthletes())
{
Console.WriteLine(a.GetName());
}
}
}
但它不会编译,因为我正在使用这个:
public void AddPlayer(BasketballPlayer player)
在 BasketballPlayer 而不是这个
public void AddPlayer(IAthlete player)
我认为它应该可以工作,因为BasketballPlayer 是一名运动员。如果我将其更改为 IAthlete,那么我可以制作另一个像这样的课程:
public class HockeyPlayer : IAthlete
{
private string name;
public string GetName()
{
return this.name;
}
public string GetSport()
{
return "Hockey";
}
public HockeyPlayer(string name)
{
this.name = name;
}
public void Run(int distance)
{
Console.WriteLine(this.name + " just ran " + distance.ToString() + " meters.");
}
}
然后在我的主要内容中执行此操作:
HockeyPlayer hp = new HockeyPlayer("Henry");
bt.AddPlayer(hp);
这在逻辑上是错误的,因为我将 HockeyPlayer 添加到了 BasketballTeam 中。它应该是这样的,我应该小心不要那样做吗?我究竟做错了什么?如何使用类图显示这一点?这会导致松耦合吗?