单态模式【其他模式】

单态模式

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

posted on 2019-01-05 12:14  竺旭东  阅读(100)  评论(0编辑  收藏  举报

导航