zoukankan      html  css  js  c++  java
  • 单态模式【其他模式】

    单态模式

    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);
        }
    }
    
  • 相关阅读:
    哇,博客开通啦
    前端与后端数据交互的方式之ajax
    apply()方法和call()方法
    元素居中的方法
    JS中兼容问题的汇总
    关于元素尺寸问题的汇总
    小案例之随机点名系统
    圣杯布局与双飞翼布局
    js自动分页加载所有数据
    浏览器工作流程
  • 原文地址:https://www.cnblogs.com/zhuxudong/p/10223978.html
Copyright © 2011-2022 走看看