首页 > 其他 > 详细

单态模式【其他模式】

时间:2019-01-05 12:58:13      阅读:124      评论:0      收藏:0      [点我收藏+]

单态模式

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

单态模式【其他模式】

原文:https://www.cnblogs.com/zhuxudong/p/10223978.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!