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

重构之后,只要一行代码就行了,而且清晰明了:

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()创建了一个实现类等。有兴趣的话自己可以看看源码。

你可能感兴趣的:(java,优化,重构)