0
点赞
收藏
分享

微信扫一扫

JAVA 编程模式:FUNCTIONAL OPTIONS

闲嫌咸贤 2022-04-14 阅读 39
java

本文章参考

Go 编程模式:Functional Options | 酷 壳 - CoolShell

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);
	}

}
举报

相关推荐

0 条评论