Java设计模式之建造者模式简明示例

建造者模式将一个复杂对象的创建和它的表示分离,使用同样的创建过程可以创建不同的表示

应用实例

Java中,建造者模式是一种常见的设计模式,StringBuilder以及okhttp3.Request都应用了建造者模式:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("https://www.linuxidc.com")
        .build();


实现

我们将要实现一个Human类的建造者模式实现。

首先创建Human类
public  class Human {
    private String name;
    private int age;
    private int weight;
    private int height;
    //-----------Setter and Getter--------------------
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
    public int getWeight() { return weight; }
    public void setWeight(int weight) { this.weight = weight; }
    public int getHeight() { return height; }
    public void setHeight(int height) { this.height = height; }
    //-----------Setter and Getter--------------------
    @Override
    public String toString(){
        return getName() + "  的年龄是  " + getAge() +
                "  的体重是  " + getWeight() + "  的身高是  " +getHeight();
    }
}


创建Builder接口
public interface Builder {
    Builder setAge(int age);
    Builder setName(String name);
    Builder setWeight(int weight);
    Builder setHeight(int height);
    Human build();
}


创建ConcreteBuilder类,使用这个类可以构建Human对象
public class ConcreteBuilder implements Builder {
    private Human human;

@Override
    public Builder setAge(int age) {
        this.human.setAge(age);
        return this;
    }
    @Override
    public Builder setName(String name) {
        this.human.setName(name);
        return this;
    }
    @Override
    public Builder setWeight(int weight) {
        this.human.setWeight(weight);
        return this;
    }
    @Override
    public Builder setHeight(int height) {
        this.human.setHeight(height);
        return this;
    }
    @Override
    public Human build() {
        return this.human;
    }
    public ConcreteBuilder(){
        this.human = new Human();
    }
}


使用演示
public class BuilderDemo {
    public static void main(String[] args){
        Human human = new ConcreteBuilder()
                .setAge(21)
                .setName("Amos")
                .setHeight(176)
                .setWeight(130)
                .build();
        System.out.println(human);
    }
}


它的输出为:
Amos  的年龄是  21  的体重是  130  的身高是  176

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/199575facbbb03982f4c16f982a9881d.html