建造者模式

9 阅读1分钟

用来创建复杂对象,

使用场景:

多个部件或者零件,都可以装配到一个对象中,但是产生的运行结果又相同。

产品类非常复杂,或者产品类中调用顺序不同产生了不同的作用。

初始化一个对象特别复杂,如使用多个构造方法,或者说有很多参数,并且都有默认值时

public record DebugProc {
    public DebugProc(decimal network, decimal cylinder, decimal sensor, decimal driver, decimal robot, decimal single, decimal whole, decimal around, decimal total) {
        Network = network;
        Cylinder = cylinder;
        Sensor = sensor;
        Driver = driver;
        Robot = robot;
        Single = single;
        Whole = whole;
        Around = around;
        Total = total;
    }
    private DebugProc() { }
    public decimal Network { get; set; }
    public decimal Cylinder { get; set; }
    public decimal Sensor { get; set; }
    public decimal Driver { get; set; }
    public decimal Robot { get; set; }
    public decimal Single { get; set; }
    public decimal Whole { get; set; }
    public decimal Around { get; set; }
    public decimal Total { get; set; }

    public class Builder {
        //9个字段
        public decimal network;
        public decimal cylinder;
        public decimal sensor;
        public decimal driver;
        public decimal robot;
        public decimal single;
        public decimal whole;
        public decimal around;
        public decimal total;
        //9个赋值方法
        public Builder Network(decimal network) {
            this.network = network;
            return this;
        }
        public Builder Cylinder(decimal cylinder) {
            this.cylinder = cylinder;
            return this;
        }
        public Builder Sensor(decimal sensor) {
            this.sensor = sensor;
            return this;
        }
        public Builder Driver(decimal driver) {
            this.driver = driver;
            return this;
        }
        public Builder Robot(decimal robot) {
            this.robot = robot;
            return this;
        }
        public Builder Single(decimal single) {
            this.single = single;
            return this;
        }
        public Builder Whole(decimal whole) {
            this.whole = whole;
            return this;
        }
        public Builder Around(decimal around) {
            this.around = around;
            return this;
        }
        public DebugProc Build() {
            DebugProc deug=new DebugProc();
            //9个字段赋值
            deug.Around = this.around;
            deug.Network = this.network;
            deug.Cylinder = this.cylinder;
            deug.Sensor = this.sensor;
            deug.Driver = this.driver;
            deug.Robot = this.robot;
            deug.Single = this.single;
            deug.Whole = this.whole;
            deug.Total = (around+network+cylinder+sensor+driver+robot+single+whole)*1/8;
            return deug;
        }
    }
}