單態模式【其他模式】
阿新 • • 發佈:2019-01-05
單態模式
public class MonoState { /** * MonoState pattern【單態模式】 * all instances of the class will have the same state * 此類的所有例項都具有相同的狀態,可以作為單例模式的替代者。 * Enforces a behavior like sharing the same state amongst all instances. * 強制在所有例項中執行共享相同狀態的行為。 */ @Test public void all() { final LoadBalancer lb1 = new LoadBalancer(); final LoadBalancer lb2 = new LoadBalancer(); lb1.service(StringRequest.of("hello")); lb2.service(StringRequest.of("world")); } } interface Request<T> { T body(); } interface Server<T> { void service(Request<T> request); } @Value(staticConstructor = "of") class StringRequest implements Request<String> { private final String body; @Override public String body() { return body; } } @Value(staticConstructor = "of") @Slf4j class StringServer implements Server<String> { private String host; private int port; @Override public void service(Request<String> request) { log.info("{} handle request {}", toString(), request.body()); } } class LoadBalancer { private static final List<Server<String>> servers = Lists.newArrayList(); private static int lastServerId; static { servers.add(StringServer.of("localhost", 1)); servers.add(StringServer.of("localhost", 2)); servers.add(StringServer.of("localhost", 3)); } public void service(Request<String> request) { Optional.ofNullable(getServer()).ifPresent(server -> server.service(request)); } private Server<String> getServer() { if (++lastServerId >= servers.size()) { lastServerId = 0; } return servers.get(lastServerId); } }