C#多构造器参数使用创建型设计模式重构高级用法示例

以下是实现链式调用和组合的完整代码示例,用于展示如何使用Builder设计模式来创建和验证对象,并实现流畅的API调用:

using System;

public class Person
{
    public string Name { get; private set; }
    public int Age { get; private set; }
    public string Address { get; private set; }
    public string Job { get; private set; }

    private Person(Builder builder)
    {
        Name = builder.Name;
        Age = builder.Age;
        Address = builder.Address;
        Job = builder.Job;
    }

    public class Builder
    {
        public string Name { get; private set; }
        public int Age { get; private set; }
        public string Address { get; private set; }
        public string Job { get; private set; }

        // 构造函数强制要求必选参数
        public Builder(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("Name is required");
            }
            Name = name;
        }

        public Builder SetAge(int age)
        {
            if (age < 0)
            {
                throw new ArgumentException("Age cannot be negative");
            }
            Age = age;
            return this;
        }

        public Builder SetAddress(string address)
        {
            if (string.IsNullOrWhiteSpace(address))
            {
                throw new ArgumentException("Address cannot be empty");
            }
            Address = address;
            return this;
        }

        public Builder SetJob(string job)
        {
            Job = job;
            return this;
        }

        public Person Build()
        {
            // 其他验证逻辑可以放在这里
            return new Person(this);
        }
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        try
        {
            var person = new Person.Builder("John Doe")
                .SetAge(30)
                .SetAddress("123 Main St")
                .SetJob("Software Engineer")
                .Build();

            Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, Address: {person.Address}, Job: {person.Job}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

说明

  1. 必选参数:在Builder的构造函数中强制传递,如Name
  2. 链式调用:每个设置器方法返回this,从而支持链式调用。
  3. 验证逻辑:在设置器方法和Build方法中进行参数验证,确保数据有效。

输出示例

如果运行上述代码,输出将会是:

Name: John Doe, Age: 30, Address: 123 Main St, Job: Software Engineer

此实现展示了如何通过Builder模式进行链式方法调用和对象组合,从而创建灵活且可扩展的对象实例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值