Java最佳实践(1)-创建对象

Java最佳实践(1)-创建对象

使用静态工厂方法创建

  1. from: 类型转换方法,它只有单个参数,返回该类型的一个相对应的实例

    Date d = Date.from(instant)
    
  2. of:聚合方法,带有多个参数,返回该类型的一个实例,把他们合并起来

    Set<Rank> faceCards=EnumSet.of(JACK, QUEEN, KING)
    
  3. valueOf:比from和of更繁琐的一种替代方法

    BigInteger prime=BigInteger.valueOf(Integer.MAX_VALUE)
    
  4. instance/getInstance:返回的实例是通过方法的参数来描述的,但是不能说与参数具有同样的值

    StackWalk luke=StackWalker.getInstance(options)
    
  5. create/newInstance:像instance/getInstance一样,但create/newInstance能够确保每次调用都返回一个新的实例

    Object newArray=Array.newInstance(classObject, arrayLen)
    
  6. getType:像getInstance一样,但是工厂方法处于不同的类中的时候使用。Type表示工厂方法所返回的对象类型

    FileStore fs=Files.getFileStore(path)
    
  7. newType:像newInstance一样,但是在工厂方法处于不同的类中的时候使用。Type表示工厂方法所返回的对象类型

    BufferedReader br=Files.newBufferedReader(path)
    
  8. type:getType和newType的简版

    List<Complain> litany=Conllections.list(legacyLitany)
    

使用建造者(Builder)模式

public class User {
    private String username;
    private String password;
    private String phone;
    private String country;
    private String city;
}

有一个如下的User类,所有属性都是String。

如果用构造器方法

public User(String username, String password, String phone, String country, String city)

因为全是String,调用方很有可能会传值错误,比如username传了password,password传了username,编译能通过,IDE也不会报错,但是运行时结果却是错的。

如果用set方法

User user=new User();
user.setUsername(username);
user.setUsername(password);
user.setUsername(phone);
user.setUsername(country);
user.setUsername(city);

需要写一大堆set,可以避免错误,但是调用方写法不够优雅。

下面使用建造者模式进行创建对象:

public class User {
    private String username;
    private String password;
    private String phone;
    private String country;
    private String city;

    public static class Builder {
        private String username;
        private String password;
        private String phone = "";
        private String country = "";
        private String city = "";

        public Builder(String username, String password) {
            this.username = username;
            this.password = password;
        }

        public Builder phone(String phone) {
            this.phone = phone;
            return this;
        }

        public Builder country(String country) {
            this.country = country;
            return this;
        }

        public Builder city(String city) {
            this.city = city;
            return this;
        }

        public User build() {
            return new User(this);
        }
    }

    private User(Builder builder) {
        this.username = builder.username;
        this.password = builder.password;
        this.phone = builder.phone;
        this.country = builder.country;
        this.city = builder.city;
    }

}

调用方写法:

User user=new User.Builder(username,password)
                .phone(phone)
                .country(county)
                .city(city)
                .build();

链式调用写法更简洁更易读。

使用try-with-resources的写法

诸如InputString, BufferedReader之类实现了Closeable接口的类可以使用如下方式创建

try(InputStream in = new ByteArrayInputStream(str.getBytes())){
    /**
    * 实现了Closeable对象的可以用try-with-resources的写法,
    * 将InputStream之类的写在try()中不需要再在finally中关闭
    */
}catch (Exception e){
    e.printStackTrace();
}

不需要再写finally去关闭,显得更简洁易懂

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容