建造者设计模式

x33g5p2x  于2021-11-16 转载在 其他  
字(1.6k)|赞(0)|评价(0)|浏览(335)

建造者模式简介

建造者模式也是用来创建对象的,有以下使用场景:
1、创建的对象的参数较多,并且允许不同的排列组合
当参数过多,并且允许排列组合的话,我们需要写大量的很长的参数列表的构造函数,看起来比较混乱。当然这种情况,可以用set()方法来解决。但是set()无法解决第二个问题
2、参数之间有约束关系,比如某个参数的值要大于另一个参数的值
当参数之间存在约束关系的时候,set()是无法保证参数之间的约束的,除非要求用户按照一定的次序来使用set()

建造者模式详解

假设我们现在需要创建一个商品类对象

public class Item{
	int maxPrice;
	int minPrice;
	String name;
	String desc;
}

minPrice 要小于maxPrice,只有name、maxPrice、minPrice是必须的。

如果要使用构造方法来创建对象的话,我们需要创建好几个不同的长的构造方法,这会使我们的代码看起来很混乱。

如果使用set()的话,因为minPrice和maxPrice之间存在约束关系,并且我们不知道用户调用set()的先后顺序,所以我们需要在每个set()都进行参数校验,这会导致代码的冗余

public class Item {

    private int minPrice;
    private int maxPrice;
    private String name;
    private String desc;

    private Item(Builder builder){
        this.maxPrice = builder.maxPrice;
        this.minPrice = builder.minPrice;
        this.name = builder.name;
        this.desc = builder.desc;
    }

    public static class Builder{

        private static final int MIN_PRICE = 100;
        private static final int MAX_PRICE = 200;

        private int minPrice;
        private int maxPrice;
        private String name;
        private String desc;

        public Builder setMinPrice(int minPrice){
            this.minPrice = minPrice;
            return this;
        }

        public Builder setMaxPrice(int maxPrice){
            this.maxPrice = maxPrice;
            return this;
        }

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

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

        public Item build(){
            if(name.isEmpty()){
                throw new IllegalArgumentException("the name is blank");
            }

            if(minPrice >= maxPrice){
                throw new IllegalArgumentException("the minPrice is higher than maxPrice");
            }

            return new Item(this);
        }
    }
}
//这样的话,我们就可以通过下面的代码来生成对象
Item item = new Item.Builder()
					.setName("dd")
					.setMaxPrice(300)
					.setMinPrice(100).build();

这样的话,我们可以通过builder()方法来控制对象中的所有参数保持正确的约束,否则会抛出异常,导致对象创建失败!!!

相关文章

微信公众号

最新文章

更多