简体   繁体   中英

Builder Design Pattern C#

there is a concept about inheritance which I do not quite understand. I have a

    protected DeveloperReport DeveloperReport; // Field
  1. Wouldn't PersonalInfoBuilder be able to access that field?

  2. If yes,

     public PersonalInfoBuilder MyPersonalInfo => new PersonalInfoBuilder(DeveloperReport);

    Why do I still have to pass the DeveloperReport(field) into PersonalInfoBuilder constructor, when I can just modify the protected DeveloperReport field by calling new PersonalInfoBuilder(), instead of new PersonalInfoBuilder(DeveloperReport)?

  3. And, how the concept of "return this" return the changes made to DeveloperReport(field) back to DeveloperReportBuilder?

Thanks !

    class DeveloperReport
    {
        // Properties
        public int Id { get; set; }
        public string Name { get; set; }
        public DeveloperLevel Level { get; set; }
        public int WorkingHours { get; set; }
        public int HourlyRate { get; set; }

        // Methods
        public double CalculateSalary() => WorkingHours * HourlyRate;
    }

    class DeveloperReportBuilder
    {
        protected DeveloperReport DeveloperReport;

        public PersonalInfoBuilder MyPersonalInfo => new PersonalInfoBuilder(DeveloperReport);

        public DeveloperReportBuilder()
        {
            DeveloperReport = new DeveloperReport();
        }

        // return developer report.
        public DeveloperReport Build() => DeveloperReport;
    }

    class PersonalInfoBuilder : DeveloperReportBuilder
    {
        public PersonalInfoBuilder(DeveloperReport report)
        {
            DeveloperReport = report;
        }

        public PersonalInfoBuilder()
        {

        }

        public PersonalInfoBuilder NameIs(string name)
        {
            DeveloperReport.Name = name;
            return this;
        }

        public PersonalInfoBuilder IDis(int id)
        {
            DeveloperReport.Id = id;
            return this;
        }
    }

You only have to pass the report instance if you want to have both instances of DeveloperReportBuilder and PersonalInfoBuilder have acces to the same instance of DeveloperReport .

Inheritance will not copy the instance values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM