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);
        }
    }
    
  • 相关阅读:
    Linux -- touch
    Linux -- ls
    Linux -- 手动新建用户
    Linux -- id
    Linux -- chfn
    Linux -- finger
    Linux -- newgrp
    浅谈java中线程和操作系统线程
    java虚拟机入门(五)- 常见垃圾回收器及jvm实现
    java虚拟机入门(四)-垃圾回收的故事
  • 原文地址:https://www.cnblogs.com/zhuxudong/p/10223978.html
Copyright © 2011-2022 走看看