android中builder模式的使用
变种的Builder模式的自动化生产实现:
AS安装插件 Innerbuilde
新建User类
public class User { private final String name; //必选 private final String age; private final String phone; private final String dec; }
右键-->Generate-->Builder生产,然后稍作修改即可
package com.loaderman.example; public class User { private final String name; private final String age; private final String phone; private final String dec; private User(Builder builder) { name = builder.name; //必选 age = builder.age; phone = builder.phone; dec = builder.dec; } public static final class Builder { private final String name;//必选 private String age; private String phone; private String dec; public Builder(String name) { this.name=name; } public Builder age(String val) { age = val; return this; } public Builder phone(String val) { phone = val; return this; } public Builder dec(String val) { dec = val; return this; } public User build() { return new User(this); } } }
使用:
User user = new User .Builder("哈哈") .age("12") .dec("描述") .build();
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!