小试牛刀-自己写一个构造器
定义:构造器是通过方法分离的形式传入参数,最后一步调用build()返回生成构造的对象。
我自定义了一个构造一个屋子的构造器,它能灵活根据需求生成属性。
/** * 房子构造器 * Created on 2023/07/24 by Qi. */ public class HouseBuilder { private final House house; public HouseBuilder() { this.house = new House(); } public static HouseBuilder create(){ return new HouseBuilder(); } public HouseBuilder woodType(int woodType){ this.house.getRoof().setWoodType(woodType); return this; } public HouseBuilder door(String door){ this.house.setDoor(door); return this; } public HouseBuilder windows(String windows){ this.house.setWindows(windows); return this; } public HouseBuilder rooms(int room){ this.house.setRooms(room); return this; } public House build(){ return house; } public static void main(String[] args) { House house = HouseBuilder.create() .door("白色木门") .rooms(2) .windows("3个窗户") .woodType(1) .build(); System.out.println(); } }
Bean类:
/** * 房子的构造 * Created on 2023/07/24 by Qi. */ @Data public class House { /** * 屋顶 */ private Roof roof; /** * 房间 1:1个房间 2:两个房间 */ private int rooms; /** * 窗户种类 CIRCLE SQUARE */ private String windows; /** * 门的种类 BIG SMALL */ private String door; public Roof getRoof(){ return roof == null ? roof =new Roof():roof; } }
/** * 房顶 * Created on 2023/07/24 by Qi. */ @Data public class Roof { /** * 1: 榉木 2:黄花梨 3:檀木 */ private int woodType; /** * 屋顶高度 : 厘米 */ private int height; /** * 形状 */ private int shape; }
人前不露怯,
远足不露财,
内外当整洁,
自奉须俭约。