深入浅出细说创建型设计模式(二)--生成器模式

194 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

前言

 每天一小步,成功一大步。大家好,我是程序猿小白 GW_gw,很高兴能和大家一起学习每天小知识。

以下内容部分来自于网络,如有侵权,请联系我删除,本文仅用于学习交流,不用作任何商业用途。

摘要

本文主要介绍创建型模式中的生成器(Builder)模式。通过生成器模式中的五大角色(包含客户端)来具体介绍。分别是:(生成器)Builder、(具体建造工具)ConcreteBuilder、(指挥者)Director、(产品,被构建的对象)Product。客户端(Client)

构建器模式(Builder)

将一个复杂对象的构建与它的表示相分离,从而使得同样的构建过程可以创建不同的表示。

例如:同样的制造汽车的过程,可以制造出宝马和奔驰。

UML图:

image.png

具体代码:

产品:

 public class Car {
     private String wheel;
     private String shell;
 ​
     public String getWheel() {
         return wheel;
     }
 ​
     public void setWheel(String wheel) {
         this.wheel = wheel;
     }
 ​
     public String getShell() {
         return shell;
     }
 ​
     public void setShell(String shell) {
         this.shell = shell;
     }
 }

生成器:

 /**
  * @author GW_gw
  * Build a Builder interface
  * Contains the various methods for making up the product and
  * the methods for obtaining the final product
  */
 public interface CarBuilder {
     /**
      * Build the wheels of a car
      */
     void buildWheel();
 ​
     /**
      * Build the shell of the car
      */
     void buildShell();
 ​
     /**
      * @return a specific car
      * get final product
      */
     Car buildCar();
 }

具体建造工具:

 /**
  * @author Gw_gw
  * specific Builder tool
  */
 public class BWMBuilder implements CarBuilder {
     Car car;
 ​
     public BWMBuilder() {
         car = new Car();
     }
 ​
     @Override
     public void buildWheel() {
         car.setWheel("Wheel");
     }
 ​
     @Override
     public void buildShell() {
         car.setShell("Shell");
     }
 ​
     @Override
     public Car buildCar() {
         return car;
     }
 }
 ​

指挥者:

 /**
  * @author Gw_gw
  * The Director, what constructor does the Builder use
  */
 public class CarDirector {
     public Car constructCarDirector(CarBuilder carBuilder) {
         carBuilder.buildWheel();
         carBuilder.buildShell();
         return carBuilder.buildCar();
     }
 }
 ​

具体产品:

 public class BWM extends Car{
 }

指挥者使用建造工具用生成器构造对象,得到客户端产品。

结语

以上就是关于生成器(Builder)的一些基础知识,如有不正之处,欢迎掘友们斧正。