建造者模式
Posted chenziyue
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了建造者模式相关的知识,希望对你有一定的参考价值。
建造者模式
一般用于不可变对象 比如配置文件
// 创建打印机类 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(); }
以上是关于建造者模式的主要内容,如果未能解决你的问题,请参考以下文章