编程语言
首页 > 编程语言> > 如何优雅构建一个很多参数的java对象

如何优雅构建一个很多参数的java对象

作者:互联网

构建者模式,参考 go-elastic-client对象的构建,由于参数非常多而且后期会有比较大的变动的可能

正常的想法:

function build(a,b,c,d,e,f,g,h,i,j...)

function build(a,b,c,...)

function build(a,b,...)

随着参数的增多 builder方法会一直增多

并且可变参总是不够灵活,有时候需要2个或者更多个可变参数

优雅一些的写法:

package com.example.one.po;

import lombok.Data;

@Data
public class LoggerDetail {

    private String userName;
    private String userIp;
    private String level;

    public static LoggerDetail builder(String userName,OptionFunc ...optionFunc){
        LoggerDetail loggerDetail = new LoggerDetail();
        loggerDetail.setUserName(userName);
        for (OptionFunc func : optionFunc) {
            func.set(loggerDetail);
        }
        return loggerDetail;
    }
}

定义的接口:

package com.example.one.po;

public interface OptionFunc {
    void set(LoggerDetail loggerDetail);
}

后续就是不断的实现 OptionFunc 进行扩充参数

level :

package com.example.one.po;

public class SetLevel implements OptionFunc{

    private String level;
    @Override
    public void set(LoggerDetail loggerDetail) {
        loggerDetail.setLevel(level);
    }
    public SetLevel(String level){
        this.level = level;
    }
}

userIp

package com.example.one.po;

public class SetUserIp implements OptionFunc{

    private String userIp;

    @Override
    public void set(LoggerDetail loggerDetail) {
        loggerDetail.setUserIp(userIp);
    }

    public SetUserIp(String userIp){
        this.userIp = userIp;
    }
}

调用的方式:

@Test
    public void TestLoggerDetail (){
        LoggerDetail loggerDetail = LoggerDetail.builder(
                "jack",
                new SetUserIp("127.0.0.1"),
                new SetLevel("warn")
        );
        System.out.println(loggerDetail);
}

 

 

TRANSLATE with x English
Arabic Hebrew Polish
Bulgarian Hindi Portuguese
Catalan Hmong Daw Romanian
Chinese Simplified Hungarian Russian
Chinese Traditional Indonesian Slovak
Czech Italian Slovenian
Danish Japanese Spanish
Dutch Klingon Swedish
English Korean Thai
Estonian Latvian Turkish
Finnish Lithuanian Ukrainian
French Malay Urdu
German Maltese Vietnamese
Greek Norwegian Welsh
Haitian Creole Persian  
  TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back

标签:loggerDetail,java,String,level,优雅,构建,userIp,LoggerDetail,public
来源: https://www.cnblogs.com/xuweiqiang/p/16350241.html