构建器

2020-01-25  本文已影响0人  睦月MTK

statement:本篇内容只是建立在我目前经验的基础之上,必然有不完善甚至是不正确的地方,请谨慎阅读,如果能指出错误与不足之处,更是不甚感激


一、问题引入与分析

二、解决问题的另一种方案--构建器
interface ClassBuilder<T>{
    T build();
}

public class BuilderTest {
    //必选域
    private final int field1;
    private final int field2;
    //可选域
    private final int field3;
    //省略...
    private final int field20;
    
    public static class Builder implements ClassBuilder<BuilderTest>{
        //必选域
        private final int field1;
        private final int field2;
        //可选域
        private int field3;
        //省略...
        private int field20;
        
        public Builder(int field1 , int field2) {
            //必要的参数合法性检测代码...
            this.field1 = field1;
            this.field2 = field2;
        }
        
        public Builder setField3(int field3) {
            //必要的参数合法性检测代码...
            this.field3 = field3;
            return this;
        }
        public Builder setField20(int field20) {
            //必要的参数合法性检测代码...
            this.field20 = field20;
            return this;
        }
        
        @Override
        public BuilderTest build() {
            //必要的完整性检测代码...
            return new BuilderTest(this);
        }   
    }
    
    private BuilderTest(Builder builder) {
        this.field1 = builder.field1;
        this.field2 = builder.field2;
        this.field3 = builder.field3;
        this.field20 = builder.field20;
    }
    
    public static void main(String[] args) {
        BuilderTest test = new BuilderTest.Builder(20, 20).setField3(13).setField20(14).build();
    }
}

构建器其实就是使用一个静态内部类专门负责类字段的填充这一工作,一般取名为Builder,每个Builder都会有build方法,故将其抽离出来变成了一个接口


三、分析与总结

参考文档:
[1] 《Effective Java》

上一篇下一篇

猜你喜欢

热点阅读