JAVA BUILD模式:利用lambda表达式实现对象的构建

261 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

在我们编程中,我们会经常性的需要对一个对象(或是业务实体)进行相关的配置。比如下面这个业务实体:

class Server  {
    private String Addr     ;//必选
    private int port     ;//必选
    private String protocol ;
    private int timeout ;
    private int maxConns int
    ...
}

构建这个对象我们一般会采用build 模式来构建,但是还有另一种方法也可以灵活和优雅的实现对象的构建

代码如下:

public class Server {
	private String addr;
	private int port;
	private String protocol;
	private int timeout;
	private int maxConns;
 
	public Server(String addr, int port) {
		this.addr = addr;
		this.port = port;
	}
 
	@SafeVarargs
	public Server(String addr, int port, Consumer<Server>... options) {
		this.addr = addr;
		this.port = port;
		for (var o : options) {
			o.accept(this);
		}
	}
 
	public static Consumer<Server> protocol(String p) {
		return s -> s.protocol = p;
	}
 
	public static Consumer<Server> timeout(int timeout) {
		return s -> s.timeout = timeout;
	}
 
	public static Consumer<Server> maxConns(int maxConns) {
		return s -> s.maxConns = maxConns;
	}
 
	public String getAddr() {
		return addr;
	}
 
	public int getPort() {
		return port;
	}
 
	public String getProtocol() {
		return protocol;
	}
 
	public int getTimeout() {
		return timeout;
	}
 
	public int getMaxConns() {
		return maxConns;
	}
 
	@Override
	public String toString() {
		return String.format("Server [addr=%s, port=%s, protocol=%s, timeout=%s, maxConns=%s]", addr, port, protocol,
				timeout, maxConns);
	}
 
}

测试代码如下:

public class ServerTest {
 
	public static void main(String[] args) {
		Server s = new Server("localhost", 8080, Server.protocol("TCP"), Server.timeout(10), Server.maxConns(1000));
		System.out.println(s);
	}
 
}

本文参考如下文章:

GO 编程模式:FUNCTIONAL OPTIONS