防止对象在流畅的构建器模式C#中实例化

时间:2018-11-13 10:01:33

标签: c# design-patterns builder-pattern

我正在尝试创建流畅的构建器模式以创建用户请求,因为它具有很多参数。为简单起见,我只显示几个参数

这是我的请求类或模型

public class Request
    {
        public string UserName {  get; set; }

        public string Password {  get; set; }

        public string Token {  get; set; }


    }

这是我的构建器类,用于构建请求。

 public class RequestBuilder
    {
        private string _username;
        private string _password;
        private string _token;

        public RequestBuilder UserName(string username)
        {
            _username = username;
            return this;

        }

        public RequestBuilder Password(string password)
        {
            _password = password;
            return this;

        }

        public RequestBuilder Token(string token)
        {
            _token = token;
            return this;

        }

        public static implicit operator Request(RequestBuilder requestBuilder)
        {

            return new Request()
            {

                UserName = requestBuilder._username,
                Password = requestBuilder._password,
                Token = requestBuilder._token

            };
        }
    }

乍一看,这种方法似乎可行,但它具有

这样的安全漏洞
  1. 用户可以使用Request request = new Request()直接创建请求
  2. 如果我通过在Request类中实现参数化构造函数来限制请求类

     public Request(RequestBuilder rb){                      
            UserName = rb._username;
            Password = rb._password;
            Token    = rb._token;                    
     }
    

在这种情况下,我需要在set中创建getRequestBuilder方法,最终将如下所示公开RequestBuilder

RequestBuilder rb = new RequestBuilder();
rb._username ="test";

任何人都可以告诉我如何保护Request类以防止实例化。

1 个答案:

答案 0 :(得分:-1)

我试图找到解决方案并得到以下

  1. 使用Builder作为嵌套类
  2. Request类的默认构造函数设为私有。但是,Builder是一个嵌套类,它可以访问请求类并将其实例化
  3. 要创建Request类的对象,用户必须仅通过Builder
  

请求请求=新   Request.Builder()。UserName(“ user”)。Password(“ abc”)。Build();

示例代码

public class Request
    {
        public string UserName {   get; private set; }

        public string Password {  get; private set; }

        public string Token { get; private set; }


        private Request(){




        }

        public class Builder
        {

            private Request request = new Request();

            public Builder UserName(string username)
            {
                request.UserName = username;
                return this;

            }

            public Builder Password(string password)
            {
                request.Password = password;
                return this;

            }

            public Builder Token(string token)
            {
                request.Token = token;
                return this;

            }


            public Request Build()
            {

                return request;
            }


        }
    }