有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java关于builder模式的性能

为了测试更具可读性和易于编写,我通常在value对象中使用BuilderPattern。例如,不要以标准方式编写这个简单类:

public class MyClass{

    private String myProperty;

    public void setMyProperty(String myProperty){
       this.myProperty = myProperty;
    }
}

我喜欢这样写:

public class MyClass{

    private String myProperty;

    public MyClass setMyProperty(String myProperty){
       this.myProperty = myProperty;
       return this;
    }
}

这种方法会对性能产生不良影响吗


共 (2) 个答案

  1. # 1 楼答案

    那不是建筑商,而是建筑商

    public class MyClass { // My attrs are immutable now
    
        private final String myProperty;
    
        public MyClass(String myProperty) {
            this.myProperty = myProperty;
        }
    
        // don't add if you don't need
        public String getMyProperty() {
            return myProperty;
        }
    
        public static class Builder{
            private String myProperty;
            
            public MyClass build(){
                return new MyClass(myProperty);
            }
    
            public Builder setMyProperty(String myProperty) {
                this.myProperty = myProperty;
                return this;
            }
        }
    
        public static void main(String[] args) {
            new MyClass.Builder()
                    .setMyProperty("MyValue")
                    .build();
        }
    }
    

    这与性能无关,而是将易变性转移到构建器上,并使您的模型不变:现在您只有构建器级别的setter

  2. # 2 楼答案

    您的代码片段不是关于使用构建器模式(GoF/Bloch),而是关于使用fluent mutatorschain setters。这是一种常见的做法,对性能没有真正的影响

    关于生成器,您有额外的生成器对象。但在创建对象后,可以直接进行垃圾收集

    所以你可能会对内存使用产生一些影响。但是JVM确实经过了优化来处理这个问题