美文网首页
Builder模式

Builder模式

作者: Sunny君907 | 来源:发表于2018-02-25 14:43 被阅读0次

一、定义
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
二、适用性
在以下情况使用Builder模式:
1 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。
2 当构造过程必须允许被构造的对象有不同的表示时。
3 Builder模式要解决的也正是这样的问题:
当我们要创建的对象很复杂的时候(通常是由很多其他的对象组合而成),
我们要复杂对象的创建过程和这个对象的表示(展示)分离开来,
这样做的好处就是通过一步步的进行复杂对象的构建,
由于在每一步的构造过程中可以引入参数,使得经过相同的步骤创建最后得到的对象的展示不一样。

三、例子

public class Person {
private String name;
private int age;
private double height;
private double weight;
private Person(Builder builder){
this.name = builder.name;
this.age = builder.age;
this.height = builder.height;
this.weight = builder.weight;
}
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 double getHeight() {
    return height;
}

public void setHeight(float height) {
    this.height = height;
}

public double getWeight() {
    return weight;
}

public void setWeight(float weight) {
    this.weight = weight;
}

static class Builder{
private String name;
private int age;
private double height;
private double weight;
public Builder name(String name){
this.name = name;
return this;
}
public Builder age(int age){
this.age = age;
return this;
}
public Builder height(double height){
this.height = height;
return this;
}
public Builder weight(double weitht){
this.weight = weitht;
return this;
}
public Person build(){
return new Person(this);
}
}
}
Builder模式也是被大量的运用。比如常见的对话框的创建
四、总结

定义一个静态内部类Builder,内部的成员变量和外部类一样
Builder类通过一系列的方法用于成员变量的赋值,并返回当前对象本身(this)
Builder类提供一个build方法或者create方法用于创建对应的外部类,该方法内部调用了外部类的一个私有构造函数,该构造函数的参数就是内部类Builder
外部类提供一个私有构造函数供内部类调用,在该构造函数中完成成员变量的赋值,取值为Builder对象中对应的值

相关文章

  • 设计模式:Builder

    Builder模式基本介绍Builder模式的实现源码中的Builder模式记录 Builder模式基本介绍 Bu...

  • Builder模式

    个人博客http://www.milovetingting.cn Builder模式 模式介绍 Builder模式...

  • Android中的构建者(Builder)模式

    目录一、场景分析二、定义三、Builder模式变种-链式调用四、经典Builder模式五、用到Builder模式的...

  • Builder模式

    Builder模式?(好熟悉,貌似有说不上来),在这里好好总结一下。 Builder模式的介绍 Builder模式...

  • 设计模式之构建者模式

    Builder属于创建型设计模式 Builder定义: Separate the construction of ...

  • 建造者模式

    建造者模式 创建型模式 Director、Builder、Product建造模型 Builder负责构建Produ...

  • Builder模式及原型模式

    本文主要内容 Builder模式定义 Builder模式 原型模式定义 原型模式 本文介绍两种简单的设计模式,Bu...

  • 11.2设计模式-构建者模式-详解

    构建者模式 java的builder模式详解 builder模式在android中的实际运用 1.java的bui...

  • 第 7 章 Builder 模式 -- 组装复杂的实例

    Builder 模式 概念:组装具有复杂结构的实例可以称为 Builder 模式。 Show me the cod...

  • 设计模式--Builder

    标签(空格分隔): android 设计模式 builder 1 Builder设计模式概述 将复杂对象的构建与它...

网友评论

      本文标题:Builder模式

      本文链接:https://www.haomeiwen.com/subject/nsdrxftx.html