设计模式之建造者模式简明示例
Posted amosh
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式之建造者模式简明示例相关的知识,希望对你有一定的参考价值。
建造者模式将一个复杂对象的创建和它的表示分离,使用同样的创建过程可以创建不同的表示
应用实例
在Java中,建造者模式是一种常见的设计模式,StringBuilder以及okhttp3.Request都应用了建造者模式:
OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://www.baidu.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
以上是关于设计模式之建造者模式简明示例的主要内容,如果未能解决你的问题,请参考以下文章
设计模式从青铜到王者第八篇:创建型模式之建造者模式(BuilderPattern)