标签:可变对象 内部类 配置文件 创建 str col 打印机 不可 静态内部类
一般用于不可变对象 比如配置文件
// 创建打印机类 public class Print { // 配置写死了 private final String printName = "1"; private final String printVersion = "2"; private final String printPrice = "3"; }
新增构造方法
public Print(String printName, String printVersion, String printPrice) { this.printName = printName; this.printVersion = printVersion; this.printPrice = printPrice; }
public static void main(String[] args) { // 如果传null值 没有判断 Print print = new Print(null,null,null); }
修改代码
public class Print { private final String printName; private final String printVersion; private final String printPrice; public Print(String printName, String printVersion, String printPrice) { this.printName = printName; this.printVersion = printVersion; this.printPrice = printPrice; } // 静态内部类 static class Builder{ private String printName; private String printVersion; private String printPrice; Builder setPrintName(String printName){ this.printName = this.printName; return this; } Builder setPrintVersion(String printVersion){ this.printVersion = this.printVersion; return this; } Builder setPrintPrice(String printPrice){ this.printPrice = this.printPrice; return this; } Print builder(){ // 判断是否为空 //........... return new Print(printName,printVersion,printPrice); } } }
public static void main(String[] args) { // 更加直观 Print builder = new Print.Builder().setPrintName("1").setPrintPrice("2").setPrintVersion("3").builder(); }
标签:可变对象 内部类 配置文件 创建 str col 打印机 不可 静态内部类
原文地址:https://www.cnblogs.com/chenziyue/p/12517453.html