How to implement and extend Joshua's builder pattern in .net?

后端 未结 4 1619
粉色の甜心
粉色の甜心 2021-01-30 05:35
  • How can we implement the Builder pattern of Joshua\'s Effective Java in C#?

Below is the code I have tried, is there a better way to do this?



        
4条回答
  •  有刺的猬
    2021-01-30 06:23

    The reason to use Joshua Bloch's builder pattern was to create a complex object out of parts, and also to make it immutable.

    In this particular case, using optional, named parameters in C# 4.0 is cleaner. You give up some flexibility in design (don't rename the parameters), but you get better maintainable code, easier.

    If the NutritionFacts code is:

      public class NutritionFacts
      {
        public int servingSize { get; private set; }
        public int servings { get; private set; }
        public int calories { get; private set; }
        public int fat { get; private set; }
        public int carbohydrate { get; private set; }
        public int sodium { get; private set; }
    
        public NutritionFacts(int servingSize, int servings, int calories = 0, int fat = 0, int carbohydrate = 0, int sodium = 0)
        {
          this.servingSize = servingSize;
          this.servings = servings;
          this.calories = calories;
          this.fat = fat;
          this.carbohydrate = carbohydrate;
          this.sodium = sodium;
        }
      }
    

    Then a client would use it as

     NutritionFacts nf2 = new NutritionFacts(240, 2, calories: 100, fat: 40);
    

    If the construction is more complex this would need to be tweaked; if the "building" of calories is more than putting in an integer, it's conceivable that other helper objects would be needed.

提交回复
热议问题