简体   繁体   English

C#/ C ++中的Builder设计模式是否需要提升的访问修饰符?

[英]Builder design pattern in C#/C++ requires elevated access modifiers?

Let's say we have a Vehicle class containing a private collection of wheels, and a method AddWheel(Wheel i_WheelToAdd). 假设我们有一个Vehicle类,其中包含车轮的私有集合,以及一个AddWheel(Wheel i_WheelToAdd)方法。 without using a builder pattern, I would want this method to be protected, but because I am using the builder design pattern, I have no choice but to set it to internal (to allow the builder to add wheels). 在不使用构建器模式的情况下,我希望此方法受到保护,但是由于我使用的是构建器设计模式,因此我别无选择,只能将其设置为internal(以允许构建器添加轮子)。

what is the correct object-oriented way to fix this issue? 解决此问题的正确的面向对象方法是什么?

(the use of a nested class doesn't help me in C#/C++, assuming inside Vehicle I have a nested class 'VehicleBuilder', this doesn't give it the ability to access a private/protected member of the parent like in java) (在C#/ C ++中使用嵌套类对我没有帮助,假设在Vehicle中我有一个嵌套类'VehicleBuilder',这使它无法像在Java中那样访问父级的私有/受保护成员。 )

What I would do is have the Vehicle class take the builder as a constructor parameter and be responsible for ingesting all the settings created on the builder. 我要做的是让Vehicle类将构建器作为构造器参数,并负责提取在构建器上创建的所有设置。 I think of the builder as building all the parameters needed and getting the appropriate object back, it does not have to actually have to handle setting the properties directly. 我认为构建器是构建所需的所有参数并获取适当的对象,实际上不必直接处理设置属性。 That way you can put the AddWheel on the builder and keep the Vehicle buttoned down. 这样,您可以将AddWheel放在构建器上,并保持Vehicle处于按下状态。

public class Vehicle{
    public List<Wheel> Wheels {get; private set;}
    internal Vehicle(VehicleBuilder builder)
    {
         Wheels = builder.Wheels;
         //Set other useful properties...
    }
}

public class VehicleBuilder()
{
    private List<Wheel> _wheels = new List<Wheel>;
    internal List<Wheel> Wheels
    {
      get{return _wheels;}
    }
    public void AddWheel(Wheel wheelToAdd)
    {
        _wheels.Add(wheelToAdd);
    }
   public Vehicle GetVehicle()
   {
      return new Vehicle(this);
   }
}

One way is to make the builder as an inner class that gets exposed from the object itself: 一种方法是使构建器成为从对象本身暴露的内部类:

class Vehicle
{
  ⁞
  class VehicleBuilder
  {
    ⁞
  }
  private Vehicle(...) { ... }
  public VehicleBuilder New => new VehicleBuilder();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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