当前位置:网站首页>[creation mode] builder mode

[creation mode] builder mode

2022-06-11 15:23:00 Evader1997

Look at a picture and relax

 Insert picture description here

   I found a moving picture from Du Niang , It is clear that this is an assembly line . The Yellow worker is responsible for putting the box into the bag , The blue worker is responsible for sealing the bag . Everyone in the assembly line should know , Everyone is responsible for one process , A complete product needs to go through all the assembly line workers . This real-world example can just help you understand the builder model .

Builder pattern

  《 Big talk design patterns 》 Definition : Builder pattern , Will be a complex object of Build is separate from its presentation , So that the same build process can create different representations

   This definition may not be well understood by those who are exploring design patterns , It can be simply understood as ,new Is to combine the construction and representation of objects ,= The one on the left can be understood as , and = Dexter new Xxx(a,b) It's the production process . So the builder pattern separates the presentation from the production process , There are two advantages to this :

  1. One is to ensure that when creating complex objects ** The production steps are specified ,** It ensures that the created objects conform to the rules ( The following case will explain )
  2. The decoupling of product construction process is realized ( Client failed new To create the object )

Car making and car making manual cases

   This case reflects Create different kinds of cars And Different kinds of car manuals . Say important things three times , This case is the construction of two types of products , It can better reflect some characteristics of the builder mode , You may not be able to understand it , It is recommended to read the code , I'll knock on it myself first , Then learn from the following analysis !

Project structure chart :《 Deep into design patterns 》 Case study

 Insert picture description here

Entity class and car type enumeration :Car( automobile ),Manual( Car manual ),CarType( Car type enumeration )

   The builder pattern is the creation pattern , The end result is the creation of objects , automobile (Car) And the car Handbook (Manual) Is the object to be created by the builder pattern in the case . Car type (CarType) It's a car (Car) A property required for creation .

//  The sports car , City cars ,SUV
public enum CarType {
    
    CITY_CAR, SPORTS_CAR, SUV
}
public class Car {
    
    //  Car type 
    private final CarType carType;
    //  Seat size 
    private final int seats;
    //  The engine 
    private final Engine engine;
    //  transmission 
    private final Transmission transmission;
    //  Travel meter 
    private final TripComputer tripComputer;
    //  Navigator 
    private final GPSNavigator gpsNavigator;
    //  fuel 
    private double fuel = 0;

    public Car(CarType carType, int seats, Engine engine, Transmission transmission, TripComputer tripComputer, GPSNavigator gpsNavigator) {
    
        this.carType = carType;
        this.seats = seats;
        this.engine = engine;
        this.transmission = transmission;
        this.tripComputer = tripComputer;
        if (this.tripComputer != null) {
    
            this.tripComputer.setCar(this);
        }
        this.gpsNavigator = gpsNavigator;
    }

    public CarType getCarType() {
    
        return carType;
    }

    public double getFuel() {
    
        return fuel;
    }

    public void setFuel(double fuel) {
    
        this.fuel = fuel;
    }

    public int getSeats() {
    
        return seats;
    }

    public Engine getEngine() {
    
        return engine;
    }

    public Transmission getTransmission() {
    
        return transmission;
    }

    public TripComputer getTripComputer() {
    
        return tripComputer;
    }

    public GPSNavigator getGpsNavigator() {
    
        return gpsNavigator;
    }
}

public class Manual {
    
    private final CarType carType;
    private final int seats;
    private final Engine engine;
    private final Transmission transmission;
    private final TripComputer tripComputer;
    private final GPSNavigator gpsNavigator;

    public Manual(CarType carType, int seats, Engine engine, Transmission transmission, TripComputer tripComputer, GPSNavigator gpsNavigator) {
    
        this.carType = carType;
        this.seats = seats;
        this.engine = engine;
        this.transmission = transmission;
        this.tripComputer = tripComputer;
        this.gpsNavigator = gpsNavigator;
    }

    public String print() {
    
        String info = "";
        info += "Type of car: " + carType + "\n";
        info += "Count of seats: " + seats + "\n";
        info += "Engine: volume - " + engine.getVolume() + "; mileage - " + engine.getMileage() + "\n";
        info += "Transmission: " + transmission + "\n";
        if (this.tripComputer != null) {
    
            info += "Trip Computer: Functional" + "\n";
        } else {
    
            info += "Trip Computer: N/A" + "\n";
        }
        if (this.gpsNavigator != null) {
    
            info += "GPS Navigator: Functional" + "\n";
        } else {
    
            info += "GPS Navigator: N/A" + "\n";
        }
        return info;
    }
}

Automotive components :Engine( The engine ),Transmission( transmission ),TripComputer ( Travel meter ),GPSNavigator( Navigator )

These classes / Enumeration corresponds to some components needed to build a car .

public class Engine {
    
    //  Volume 
    private final double volume;
    //  The mileage 
    private double mileage;
    //  start-up 
    private boolean started;

    public Engine(double volume, double mileage) {
    
        this.volume = volume;
        this.mileage = mileage;
    }
    
    public void on() {
    
        started = true;
    }

    public void off() {
    
        started = false;
    }

    public boolean isStarted() {
    
        return started;
    }

    public void go(double mileage) {
    
        if (started) {
    
            this.mileage += mileage;
        } else {
    
            System.out.println("Cannot go(), you must start engine first!");
        }
    }

    public double getVolume() {
    
        return volume;
    }

    public double getMileage() {
    
        return mileage;
    }
}
/** *  transmission  ( One speed , manual , automatic , semi-automatic ) */
public enum Transmission {
    
    SINGLE_SPEED, MANUAL, AUTOMATIC, SEMI_AUTOMATIC
}
public class TripComputer {
    
    private Car car;

    public void setCar(Car car) {
    
        this.car = car;
    }

    public void showFueLevel() {
    
        System.out.println("Fuel level:" + car.getFuel());
    }
}

public class GPSNavigator {
    
    //  Route 
    private String route;

    public GPSNavigator() {
    
        this.route = "221b, Baker Street, London to Scotland Yard, 8-10 Broadway, London";
    }

    public GPSNavigator(String manualRoute) {
    
        this.route = manualRoute;
    }

    public String getRoute() {
    
        return route;
    }
}

Abstract builder and concrete builder :Builder( Abstract construction interface ),CarBuilder( Specific builder ),CarManualBuilder( Specific builder )

  • Builder: Abstract construction interface , Defines how to build a car / All process methods of the manual
  • CarBuilder: The specific builder of the car , Specific car builders , The interior provides a getResult() Method to get a Car object
  • CarManualBuilder: The specific builder of the automobile manual , Specific manual builder , The interior provides a getResult() Method to get a Manual object
public interface Builder {
    
    void setCarType(CarType type); //  models 

    void setSeats(int seats);      //  seat 

    void setEngine(Engine engine); //  The engine 

    void setTransmission(Transmission transmission); //  transmission 

    void setTripComputer(TripComputer tripComputer); //  hodometer 

    void setGPSNavigator(GPSNavigator gpsNavigator); //  Navigator 
}
public class CarBuilder implements Builder {
    

    private CarType type;
    private int seats;
    private Engine engine;
    private Transmission transmission;
    private TripComputer tripComputer;
    private GPSNavigator gpsNavigator;

    @Override
    public void setCarType(CarType type) {
    
        this.type = type;
    }

    @Override
    public void setSeats(int seats) {
    
        this.seats = seats;
    }

    @Override
    public void setEngine(Engine engine) {
    
        this.engine = engine;
    }

    @Override
    public void setTransmission(Transmission transmission) {
    
        this.transmission = transmission;
    }

    @Override
    public void setTripComputer(TripComputer tripComputer) {
    
        this.tripComputer = tripComputer;
    }

    @Override
    public void setGPSNavigator(GPSNavigator gpsNavigator) {
    
        this.gpsNavigator = gpsNavigator;
    }

    public Car getResult() {
    
        return new Car(type, seats, engine, transmission, tripComputer, gpsNavigator);
    }
}
public class CarManualBuilder implements Builder {
    

    private CarType type;
    private int seats;
    private Engine engine;
    private Transmission transmission;
    private TripComputer tripComputer;
    private GPSNavigator gpsNavigator;

    @Override
    public void setCarType(CarType type) {
    
        this.type = type;
    }

    @Override
    public void setSeats(int seats) {
    
        this.seats = seats;
    }

    @Override
    public void setEngine(Engine engine) {
    
        this.engine = engine;
    }

    @Override
    public void setTransmission(Transmission transmission) {
    
        this.transmission = transmission;
    }

    @Override
    public void setTripComputer(TripComputer tripComputer) {
    
        this.tripComputer = tripComputer;
    }

    @Override
    public void setGPSNavigator(GPSNavigator gpsNavigator) {
    
        this.gpsNavigator = gpsNavigator;
    }

    public Manual getResult(){
    
        return new Manual(type, seats, engine, transmission, tripComputer, gpsNavigator);
    }
}

Supervisor control generator :Director ( commander )

   Three methods are defined in the commander , You can clearly see that the actual assignment is to the incoming builder , The three methods create different cars / manual , Is it a production vehicle or a production manual , The commander doesn't know , It depends on the specific builder . however No matter who the builder is , What the commander performs is an assembly line operation , As shown in the figure at the beginning , A brief analysis :

  1. constructSportsCar( Build sports cars ) Construction process :setCarType( Determine the vehicle type ) ------> setSeats( Build car seating capacity ) ------> setEngine( Build car engines ) ------> setTransmission( Build automobile gearboxes ) ------> setTripComputer( Build a car trip meter ) ------> setGPSNavigator( Build a navigator )
  2. constructCityCar( Building city cars ) Construction process :setCarType( Determine the vehicle type ) ------> setSeats( Build car seating capacity ) ------> setEngine( Build car engines ) ------> setTransmission( Build automobile gearboxes ) ------> setTripComputer( Build a car trip meter ) ------> setGPSNavigator( Build a navigator )
  3. constructCityCar( build SUV) Construction process :setCarType( Determine the vehicle type ) ------> setSeats( Build car seating capacity ) ------> setEngine( Build car engines ) ------> setTransmission( Build automobile gearboxes ) ------> setGPSNavigator( Build a navigator )

   We found that building SUV There are only five steps , There is no such step as building a trip meter ( Actually a lot of SUV When leaving the factory, there is no travel meter , You need to add extra ). This example is just right here , That is to say, in the process of construction , Not all products need to complete the lottery builder (Builder) All the steps defined in , It can be realized on demand , It's very flexible .

   Another advantage is The process of building objects is orderly , It is embodied in the following methods , We know that program execution is from top to bottom , This ensures that the objects created by the program are free of problems . Instead of using the builder pattern, we create a Car The flow of the object is :1, Take those components first new come out 2, Call again Car To create objects . So let's think about this , If the first 1 We have fewer objects in the three steps set A value , What happens ? So your component is incomplete , An incomplete component to build a car , Naturally, there is something wrong with this car . The builder pattern guarantees the integrity of the construction process by using the execution order of the code in a method .

public class Director {
    

    public void constructSportsCar(Builder builder) {
    
        builder.setCarType(CarType.SPORTS_CAR);
        builder.setSeats(2);
        builder.setEngine(new Engine(3.0, 0));
        builder.setTransmission(Transmission.SEMI_AUTOMATIC);
        builder.setTripComputer(new TripComputer());
        builder.setGPSNavigator(new GPSNavigator());
    }

    public void constructCityCar(Builder builder) {
    
        builder.setCarType(CarType.CITY_CAR);
        builder.setSeats(2);
        builder.setEngine(new Engine(1.2, 0));
        builder.setTransmission(Transmission.AUTOMATIC);
        builder.setTripComputer(new TripComputer());
        builder.setGPSNavigator(new GPSNavigator());
    }

    public void constructSUV(Builder builder) {
    
        builder.setCarType(CarType.SUV);
        builder.setSeats(4);
        builder.setEngine(new Engine(2.5, 0));
        builder.setTransmission(Transmission.MANUAL);
        builder.setGPSNavigator(new GPSNavigator());
    }
}

summary

   The actual development of the builder model is not common , But in JDK There is its shadow in , such as StringBuffer And StringBuilder Of append The method is to adopt the builder mode , The builder's model is inscrutable , In fact, we can realize the builder mode without a commander , This article does not expand . This pattern separates the object representation from the construction process , Realize decoupling , And ensure that complex objects ( The properties of an object are also objects ) Correctness of creation .

UML Class diagram

 Insert picture description here

原网站

版权声明
本文为[Evader1997]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111518260331.html