对象创建&等效属性签名。这满足要求吗?

时间:2014-12-30 11:15:50

标签: c# design-patterns refactoring design-principles

我试图升级我在C#中的一般课程设计技能,并希望你们揭示我可能拥有的代码气味。 (希望Stackoverflow.com允许进行一般性讨论)

关于This Tutorial,我把它包装到C#并尝试链接构​​造函数,避免使用相同的属性签名并以正确的方式解决它,而不重复代码。

本教程中的问题: Running Back Wide Receiver 将使用相同的属性签名。每个玩家角色的多个构造都会导致错误。相反,您可以使用对象创建 下面,我是如何解决它的。

足球运动员课程:

public class FootballPlayer
{
    public double PasserRating { get; set; }    // Specific to QBs
    public int RushingYards { get; set; }       // Specific to RBs & QBs
    public int ReceivingYards { get; set; }     // Specific to RBs & WRs
    public int TotalTackles { get; set; }       // Specific to DEF
    public int Interceptions { get; set; }      // Specific to DEF
    public int FieldGoals { get; set; }         // Specific to Kickers
    public double AvgPunt { get; set; }         // Specific to Punters
    public double AvgKickoffReturn { get; set; }// Specific to Special Teams
    public double AvgPuntreturn { get; set; }   // Specific to Special Teams

    private FootballPlayer() : this(0.0, 0, 0, 0, 0, 0, 0.0, 0.0, 0.0) { }

    private FootballPlayer(double passerRating, int rushingYards, int receivingYards, int totalTackles, int interceptions, int fieldGoals, double avgPunt, double avgKickoffReturn, double avgPuntreturn)
    {
        PasserRating = passerRating;
        RushingYards = rushingYards;
        ReceivingYards = receivingYards;
        TotalTackles = totalTackles;
        Interceptions = interceptions;
        FieldGoals = fieldGoals;
        AvgPunt = avgPunt;
        AvgKickoffReturn = avgKickoffReturn;
        AvgPuntreturn = avgPuntreturn;
    }

    public static FootballPlayer CreateQb(double passerRating, int rushingYards)
    {
        return new FootballPlayer
        {
            PasserRating = passerRating,
            RushingYards = rushingYards
        };
    }

    public static FootballPlayer CreateRb(int rushingYards)
    {
        return new FootballPlayer
        {
            RushingYards = rushingYards
        };
    }

    public static FootballPlayer CreateWr(int receivingYards)
    {
        return new FootballPlayer
        {
            ReceivingYards = receivingYards
        };
    }
}

程序:

class Program
{
    static void Main()
    {
        var aaronRodgers = FootballPlayer.CreateQb(132.0, 259);
        var drewBrees = FootballPlayer.CreateQb(129.6, 244);

        Console.WriteLine("Aaron Rodgers passer Rating: {0}", aaronRodgers.PasserRating);
        // OUTPUT: Aaron Rodgers passer Rating: 132

        Console.WriteLine("Drew Brees passer Rating: {0}", drewBrees.PasserRating);
        // OUTPUT: Drew Brees passer Rating: 129.6

        Console.ReadLine();
    }
}

你们有没有说要走的路? 或者我应该考虑什么?

0 个答案:

没有答案