将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

    1. public class Build {
    2. static class Student{
    3. String name = null ;
    4. int number = -1 ;
    5. String sex = null ;
    6. public Student(Builder builder){
    7. this.name=builder.name;
    8. this.number=builder.number;
    9. this.sex=builder.sex;
    10. }
    11. static class Builder{
    12. String name = null ;
    13. int number = -1 ;
    14. String sex = null ;
    15. public Builder setName(String name){
    16. this.name=name;
    17. return this;
    18. }
    19. public Builder setNumber(int number){
    20. this.number=number;
    21. return this;
    22. }
    23. public Builder setSex(String sex){
    24. this.sex=sex;
    25. return this;
    26. }
    27. public Student build(){
    28. return new Student(this);
    29. }
    30. }
    31. }
    32. public static void main(String[] args) {
    33. Student A = new Student.Builder()
    34. .setName("张 三")
    35. .setNumber(1)
    36. .build();
    37. Student B = new Student.Builder()
    38. .setSex("男")
    39. .setName("李四")
    40. .build();
    41. System.out.println(A.name+" "+A.number+" "+A.sex);
    42. System.out.println(B.name+" "+B.number+" "+B.sex);
    43. }
    44. }
    1. 相同的方法,不同的执行顺序,产生不同的事件结果时,可以采用建造者模式。
    2. 多个部件或零件,都可以装配到一个对象中,但是产生的运行结果又不相同时,则可以使用该模式。
    3. 产品类非常复杂,或者产品类中的调用顺序不同产生了不同的效能,这个时候使用建造者模式非常合适。