设计模式之---建造者模式

in steemit •  7 years ago  (edited)


建造者模式(Builder Pattern)

定义

Separate the construction of a complex object from its repre-sentation so that the same construction process can create differ-ent representations.
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
类图:
从类图可以看到主要有四个类:

  • 产品类 Product
  • 抽象建造类 Builder
  • 具体建造类 ConcreteBuider
  • 导演类 Director

优点

  • 封装建造细节
  • 建造者相互独立,容易扩展
  • 简化构建过程
    实现代码
public abstract class Builder {
    public abstract void setPart();
 public abstract Product buildProduct();

}
public class ConcreteProduct extends Builder  {
    private Product product =new Product();
 public void setPart() {

    }

    public Product buildProduct() {
        return product;
  }

}
public class Director {
    private Builder builder=new ConcreteProduct();
 public Product getAProduct(){
        builder.setPart();
 return builder.buildProduct();
  }
}
public class Product {
    public void doSomething(){
        System.out.println("doSomething");
  }
}

测试类

public class Test {
    public static void main(String[] args) {
        Director director=new Director();
  director.getAProduct().doSomething();
  }
}

输出结果

doSomething

应用场景

  • 产品类比较复杂,调用顺序的不同产出不同
  • 相同的方法,不同的执行顺序,产出不同

参考 : 百度百科

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!