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

后端 未结 4 1626
粉色の甜心
粉色の甜心 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:30

    In Protocol Buffers, we implement the builder pattern like this (vastly simplified):

    public sealed class SomeMessage
    {
      public string Name { get; private set; }
      public int Age { get; private set; }
    
      // Can only be called in this class and nested types
      private SomeMessage() {}
    
      public sealed class Builder
      {
        private SomeMessage message = new SomeMessage();
    
        public string Name
        {
          get { return message.Name; }
          set { message.Name = value; }
        }
    
        public int Age
        {
          get { return message.Age; }
          set { message.Age = value; }
        }
    
        public SomeMessage Build()
        {
          // Check for optional fields etc here
          SomeMessage ret = message;
          message = null; // Builder is invalid after this
          return ret;
        }
      }
    }
    

    This isn't quite the same as the pattern in EJ2, but:

    • No data copying is required at build time. In other words, while you're setting the properties, you're doing so on the real object - you just can't see it yet. This is similar to what StringBuilder does.
    • The builder becomes invalid after calling Build() to guarantee immutability. This unfortunately means it can't be used as a sort of "prototype" in the way that the EJ2 version can.
    • We use properties instead of getters and setters, for the most part - which fits in well with C# 3's object initializers.
    • We do also provide setters returning this for the sake of pre-C#3 users.

    I haven't really looked into inheritance with the builder pattern - it's not supported in Protocol Buffers anyway. I suspect it's quite tricky.

提交回复
热议问题