Java最適化コンストラクタを考慮したオブジェクトの作成


最近プロジェクトをするとき、CartMessageというオブジェクトを新規作成する必要があります.CartMessageはメソッドパラメータとしてのみ使用されます.CartMessageを構築する場合は、再構築する前の方法は似ています.
CartMessage msg = new CartMessage();
msg.setA();
msg.setB();
msg.setC();
...
helpCartService.sendMsgToWebSocket(msg);

setの方法では煩雑で,複数行を占有し,簡潔に書かれていないことが分かった.Java Effecttiveの本でオブジェクトの構築に関するアドバイスを無視します.コンストラクタ方式を思い出しました.まず、CartMessageにBuilderビルダーを追加します.
    public static class Builder{
        private CartMessage cartMessage;
        public Builder(){
            cartMessage = new CartMessage();
        }
        public Builder entityId(String entityId){
            cartMessage.setEntityId(entityId);
            return this;
        }
        public Builder seatCode(String seatCode){
            cartMessage.setSeatCode(seatCode);
            return this;
        }
        public Builder customerId(String customerId){
            cartMessage.setCustomerRegisterId(customerId);
            return this;
        }
        public Builder orderId(String orderId){
            cartMessage.setOrderId(orderId);
            return this;
        }
        public CartMessage build(){
            return cartMessage;
        }
    }

再構築後、コードを1行だけで済み、明確になります.
helpCartService.sendMsgToWebSocket(new CartMessage.Builder().
                    entityId(entityId).seatCode(seatCode).customerId(customerRegisterId).orderId(orderId).build());

コンストラクタには多くの変形があり、zookeeperクライアントCuratorのclientの作成もコンストラクタを使用します.
    static CuratorFramework client = CuratorFrameworkFactory.builder()
            .connectString("localhost:2181")
            .sessionTimeoutMs(5000)
            .retryPolicy(retryPolicy)
            .build();

builder()は静的メソッドで、コンストラクタを返します.
   public static Builder builder()
    {
        return new Builder();
    }

ビルダーは次のとおりです.
 public static class Builder {
        private EnsembleProvider ensembleProvider;
        private int sessionTimeoutMs = DEFAULT_SESSION_TIMEOUT_MS;
        private int connectionTimeoutMs = DEFAULT_CONNECTION_TIMEOUT_MS;
        private int maxCloseWaitMs = DEFAULT_CLOSE_WAIT_MS;
        private RetryPolicy retryPolicy;
        private ThreadFactory threadFactory = null;
        private String namespace;
        private List<AuthInfo> authInfos = null;
        private byte[] defaultData = LOCAL_ADDRESS;
        private CompressionProvider compressionProvider = DEFAULT_COMPRESSION_PROVIDER;
        private ZookeeperFactory zookeeperFactory = DEFAULT_ZOOKEEPER_FACTORY;
        private ACLProvider aclProvider = DEFAULT_ACL_PROVIDER;
        private boolean canBeReadOnly = false;
        /** * Apply the current values and build a new CuratorFramework * * @return new CuratorFramework */
        public CuratorFramework build()
        {
            return new CuratorFrameworkImpl(this);
        }
        /** * Apply the current values and build a new temporary CuratorFramework. Temporary * CuratorFramework instances are meant for single requests to ZooKeeper ensembles * over a failure prone network such as a WAN. The APIs available from {@link CuratorTempFramework} * are limited. Further, the connection will be closed after 3 minutes of inactivity. * * @return temp instance */
        public CuratorTempFramework buildTemp()
        {
            return buildTemp(DEFAULT_INACTIVE_THRESHOLD_MS, TimeUnit.MILLISECONDS);
        }
...

builderには、buildTemp()が一時オブジェクトを構築したり、build()が実装クラスを作成したりするなど、多くの構築方法があることがわかります.興味があれば自分でソースを見てもいいです.