标签:this 构建 java server style his article stat dog
1 public class Dog { 2 private final String name; // 名称 3 private final String sex; // 性别 4 private final int age; // 年龄 5 private final String fur; // 毛发 6 private final String breed; // 品种 7 private final float weight; // 体重 8 private final float height; // 身高 9 10 private Dog(Builder builder) { // 私有构造方法,入参为内部类对象 11 name = builder.name; 12 sex = builder.sex; 13 age = builder.age; 14 fur = builder.fur; 15 breed = builder.breed; 16 weight = builder.weight; 17 height = builder.height; 18 } 19 20 @Override 21 public String toString() { 22 return "Dog{" + "name=‘" + name + ‘\‘‘ + ", sex=‘" + sex + ‘\‘‘ + ", age=" + age + ", fur=‘" + fur + ‘\‘‘ 23 + ", breed=‘" + breed + ‘\‘‘ + ", weight=" + weight + ", height=" + height + ‘}‘; 24 } 25 26 public static class Builder { 27 private final String name; // 名称 28 private String sex; // 性别 29 private int age; // 年龄 30 private String fur; // 毛发 31 private String breed; // 品种 32 private float weight; // 体重 33 private float height; // 身高 34 35 public Builder(String name) { 36 this.name = name; 37 } 38 39 public Builder sex(String sex) { 40 this.sex = sex; 41 return this; 42 } 43 44 public Builder age(int age) { 45 this.age = age; 46 return this; 47 } 48 49 public Builder fur(String fur) { 50 this.fur = fur; 51 return this; 52 } 53 54 public Builder breed(String breed) { 55 this.breed = breed; 56 return this; 57 } 58 59 public Builder weight(float weight) { 60 this.weight = weight; 61 return this; 62 } 63 64 public Builder height(float height) { 65 this.height = height; 66 return this; 67 } 68 69 public Dog build() { 70 return new Dog(this); 71 } 72 } 73 }
public class Client { public static void main(String args[]) { Dog dog = new Dog.Builder("花花").age(1).height(50.0f).weight(50.0f).sex("boy").breed("拉布拉多").fur("yellow") .build(); System.out.println(dog.toString()); } }
标签:this 构建 java server style his article stat dog
原文地址:https://www.cnblogs.com/xiashiwendao/p/9131716.html