码迷,mamicode.com
首页 > 其他好文 > 详细

建造者模式

时间:2020-03-18 15:57:22      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:可变对象   内部类   配置文件   创建   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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!