建造者模式

代码如下:

public class CeShi {
    public static void main(String[] args) {
       JianZaoZhe jianZaoZhe=new JianZaoZhe.Builder().setName("laliang").setAge(24).setFenShu(100).build();
       System.out.println(jianZaoZhe.toString());
    }
}
class JianZaoZhe{
    private String name;
    private int age;
    private float fenShu;
    private JianZaoZhe(){
    }

    @Override
    public String toString() {
        return name+","+age+","+fenShu;
    }

    public static class Builder{//建造者模式的内部类必须是静态的才行,因为外部类构造方法是private,所以只有内部类是static修饰的,才能和外部类脱离开来
        private JianZaoZhe jianZaoZhe;
        public Builder(){
            jianZaoZhe=new JianZaoZhe();
        }
        public Builder setName(String name){//设置外部类属性的这些方法必须是public的,对外提供接口
            jianZaoZhe.name=name;
            return this;
        }
        public Builder setAge(int age){
            jianZaoZhe.age=age;
            return this;
        }
        public Builder setFenShu(float fenShu){
            jianZaoZhe.fenShu=fenShu;
            return this;
        }
        public JianZaoZhe build(){
            return jianZaoZhe;
        }
    }
}

你可能感兴趣的:(建造者模式)