設計模式——建造者模式(Java示例)

引言

生成器是一種創建型設計模式,?使你能夠分步驟創建復雜對象。

與其他創建型模式不同,?生成器不要求產品擁有通用接口。?這使得用相同的創建過程生成不同的產品成為可能。

復雜度: 中等

流行度: 流行

使用示例:?生成器模式是 Java 世界中的一個著名模式。?當你需要創建一個可能有許多配置選項的對象時,?該模式會特別有用。

生成器在 Java 核心程序庫中得到了廣泛的應用:

  • java.lang.StringBuilder#append()?(?非同步?)
  • java.lang.StringBuffer#append()?(?同步?)
  • java.nio.ByteBuffer#put()?(還有?Char-Buffer、?Short-Buffer、?Int-Buffer、?Long-Buffer、?Float-Buffer?和?Double-Buffer)
  • javax.swing.GroupLayout.Group#addComponent()
  • java.lang.Appendable的所有實現

?識別方法:?生成器模式可以通過類來識別,?它擁有一個構建方法和多個配置結果對象的方法。?生成器方法通常支持方法鏈?(例如?someBuilder.?setValueA(1).?setValueB(2).?create())。

分步制造汽車

在本例中,?生成器模式允許你分步驟地制造不同型號的汽車。

示例還展示了生成器如何使用相同的生產過程制造不同類型的產品?(汽車手冊)。

主管控制著構造順序。?它知道制造各種汽車型號需要調用的生產步驟。?它僅與汽車的通用接口進行交互。?這樣就能將不同類型的生成器傳遞給主管了。

最終結果將從生成器對象中獲得,?因為主管不知道最終產品的類型。?只有生成器對象知道自己生成的產品是什么。

?builders

?builders/Builder.java:?通用生成器接口
package refactoring_guru.builder.example.builders;import refactoring_guru.builder.example.cars.CarType;
import refactoring_guru.builder.example.components.Engine;
import refactoring_guru.builder.example.components.GPSNavigator;
import refactoring_guru.builder.example.components.Transmission;
import refactoring_guru.builder.example.components.TripComputer;/*** Builder interface defines all possible ways to configure a product.*/
public interface Builder {void setCarType(CarType type);void setSeats(int seats);void setEngine(Engine engine);void setTransmission(Transmission transmission);void setTripComputer(TripComputer tripComputer);void setGPSNavigator(GPSNavigator gpsNavigator);
}
builders/CarBuilder.java:?汽車生成器
/*** Concrete builders implement steps defined in the common interface.*/
public class CarBuilder implements Builder {private CarType type;private int seats;private Engine engine;private Transmission transmission;private TripComputer tripComputer;private GPSNavigator gpsNavigator;public void setCarType(CarType type) {this.type = type;}@Overridepublic void setSeats(int seats) {this.seats = seats;}@Overridepublic void setEngine(Engine engine) {this.engine = engine;}@Overridepublic void setTransmission(Transmission transmission) {this.transmission = transmission;}@Overridepublic void setTripComputer(TripComputer tripComputer) {this.tripComputer = tripComputer;}@Overridepublic void setGPSNavigator(GPSNavigator gpsNavigator) {this.gpsNavigator = gpsNavigator;}public Car getResult() {return new Car(type, seats, engine, transmission, tripComputer, gpsNavigator);}
}

?builders/CarManualBuilder.java:?汽車手冊生成器


/*** Unlike other creational patterns, Builder can construct unrelated products,* which don't have the common interface.** In this case we build a user manual for a car, using the same steps as we* built a car. This allows to produce manuals for specific car models,* configured with different features.*/
public class CarManualBuilder implements Builder{private CarType type;private int seats;private Engine engine;private Transmission transmission;private TripComputer tripComputer;private GPSNavigator gpsNavigator;@Overridepublic void setCarType(CarType type) {this.type = type;}@Overridepublic void setSeats(int seats) {this.seats = seats;}@Overridepublic void setEngine(Engine engine) {this.engine = engine;}@Overridepublic void setTransmission(Transmission transmission) {this.transmission = transmission;}@Overridepublic void setTripComputer(TripComputer tripComputer) {this.tripComputer = tripComputer;}@Overridepublic void setGPSNavigator(GPSNavigator gpsNavigator) {this.gpsNavigator = gpsNavigator;}public Manual getResult() {return new Manual(type, seats, engine, transmission, tripComputer, gpsNavigator);}
}

cars

?cars/Car.java:?汽車產品
/*** Car is a product class.*/
public class Car {private final CarType carType;private final int seats;private final Engine engine;private final Transmission transmission;private final TripComputer tripComputer;private final GPSNavigator gpsNavigator;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;}
}
?cars/Manual.java:?手冊產品
/*** Car manual is another product. Note that it does not have the same ancestor* as a Car. They are not related.*/
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;}
}

?cars/CarType.java

package refactoring_guru.builder.example.cars;public enum CarType {CITY_CAR, SPORTS_CAR, SUV
}

components

?components/Engine.java:?產品特征 1
/*** Just another feature of a car.*/
public class Engine {private final double volume;private double mileage;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.err.println("Cannot go(), you must start engine first!");}}public double getVolume() {return volume;}public double getMileage() {return mileage;}
}
components/GPSNavigator.java:?產品特征 2
/*** Just another feature of a car.*/
public class GPSNavigator {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;}
}
components/Transmission.java:?產品特征 3
/*** Just another feature of a car.*/
public enum Transmission {SINGLE_SPEED, MANUAL, AUTOMATIC, SEMI_AUTOMATIC
}
?components/TripComputer.java:?產品特征 4
/*** Just another feature of a car.*/
public class TripComputer {private Car car;public void setCar(Car car) {this.car = car;}public void showFuelLevel() {System.out.println("Fuel level: " + car.getFuel());}public void showStatus() {if (this.car.getEngine().isStarted()) {System.out.println("Car is started");} else {System.out.println("Car isn't started");}}
}

director

?director/Director.java:?主管控制生成器
/*** Director defines the order of building steps. It works with a builder object* through common Builder interface. Therefore it may not know what product is* being built.*/
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());}
}
Demo.java:?客戶端代碼
/*** Demo class. Everything comes together here.*/
public class Demo {public static void main(String[] args) {Director director = new Director();// Director gets the concrete builder object from the client// (application code). That's because application knows better which// builder to use to get a specific product.CarBuilder builder = new CarBuilder();director.constructSportsCar(builder);// The final product is often retrieved from a builder object, since// Director is not aware and not dependent on concrete builders and// products.Car car = builder.getResult();System.out.println("Car built:\n" + car.getCarType());CarManualBuilder manualBuilder = new CarManualBuilder();// Director may know several building recipes.director.constructSportsCar(manualBuilder);Manual carManual = manualBuilder.getResult();System.out.println("\nCar manual built:\n" + carManual.print());}}
?OutputDemo.txt:?執行結果
Car built:
SPORTS_CARCar manual built:
Type of car: SPORTS_CAR
Count of seats: 2
Engine: volume - 3.0; mileage - 0.0
Transmission: SEMI_AUTOMATIC
Trip Computer: Functional
GPS Navigator: Functional

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/214473.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/214473.shtml
英文地址,請注明出處:http://en.pswp.cn/news/214473.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【conda】利用Conda創建虛擬環境,Pytorch各版本安裝教程(Ubuntu)

TOC conda 系列: 1. conda指令教程 2. 利用Conda創建虛擬環境,安裝Pytorch各版本教程(Ubuntu) 1. 利用Conda創建虛擬環境 nolonolo:~/sun/SplaTAM$ conda create -n splatam python3.10查看結果: (splatam) nolonolo:~/sun/SplaTAM$ cond…

Java 中的 Deque 接口及其用途

文章目錄 Deque 介紹Deque 使用雙端隊列普通隊列棧 總結 在 Java 中,Deque 接口是一個雙端隊列(double-ended queue)的數據結構,它支持在兩端插入和移除元素。Deque 是 “Double Ended Queue” 的縮寫,而且它可以同時充…

Linux系統編程(一):基本概念

參考引用 Unix和Linux操作系統有什么區別?一文帶你徹底搞懂posix Linux系統編程(文章鏈接匯總) 1. Unix 和 Linux 1.1 Unix Unix 操作系統誕生于 1969 年,貝爾實驗室發布了一個用 C 語言編寫的名為「Unix」的操作系統&#xff0…

【基于LSTM的電商評論情感分析:Flask與Sklearn的完美結合】

基于LSTM的電商評論情感分析:Flask與Sklearn的完美結合 引言數據集與爬取數據處理與可視化情感分析模型構建Flask應用搭建詞云展示創新點結論 引言 在當今數字化時代,電商平臺上涌現出大量的用戶評論數據。了解和分析這些評論對于企業改進產品、服務以及…

?expect命令運用于bash?

目錄 ?expect命令運用于bash? expect使用原理 expet使用場景 常用的expect命令選項 Expect腳本的結尾 常用的expect命令選參數 Expect執行方式 單一分支語法 多分支模式語法第一種 多分支模式語法第二種 在shell 中嵌套expect Shell Here Document(內…

基于Java實驗室管理系統

基于Java實驗室管理系統 功能需求 1、實驗室設備管理:系統需要提供實驗室設備管理功能,包括設備的查詢、預訂、使用記錄、維護和報廢等。 2、實驗項目管理:系統需要提供實驗項目管理功能,包括項目的創建、審批、執行和驗收等&a…

以太坊:前世今生與未來

一、引言 以太坊,這個在區塊鏈領域大放異彩的名字,似乎已經成為了去中心化應用(DApps)的代名詞。從初期的萌芽到如今的繁榮發展,以太坊經歷了一段曲折而精彩的旅程。讓我們一起回顧一下以太坊的前世今生,以…

樹實驗代碼

哈夫曼樹 #include <stdio.h> #include <stdlib.h> #define MAXLEN 100typedef struct {int weight;int lchild, rchild, parent; } HTNode;typedef HTNode HT[MAXLEN]; int n;void CreatHFMT(HT T); void InitHFMT(HT T); void InputWeight(HT T); void SelectMi…

【算法專題】分治 - 快速排序

分治 - 快速排序 分治 - 快速排序1. 顏色分類2. 排序數組(快速排序)3. 數組中的第K個最大元素4. 庫存管理Ⅲ5. 排序數組(歸并排序)6. 交易逆序對的總數7. 計算右側小于當前元素的個數8. 翻轉對 分治 - 快速排序 1. 顏色分類 做題鏈接 -> Leetcode -75.顏色分類 題目&…

【華為數據之道學習筆記】3-5 規則數據治理

在業務規則管理方面&#xff0c;華為經常面對“各種業務場景業務規則不同&#xff0c;記不住&#xff0c;找不到”“大量規則在政策、流程等文件中承載&#xff0c;難以遵守”“各國規則均不同&#xff0c;IT能否一國一策、快速上線”等問題。 規則數據是結構化描述業務規則變量…

【Qt開發流程】之UI風格、預覽及QPalette使用

概述 一個優秀的應用程序不僅要有實用的功能&#xff0c;還要有一個漂亮美膩的外觀&#xff0c;這樣才能使應用程序更加友善、操作性良好&#xff0c;更加符合人體工程學。作為一個跨平臺的UI開發框架&#xff0c;Qt提供了強大而且靈活的界面外觀設計機制&#xff0c;能夠幫助…

利用Rclone將阿里云對象存儲遷移至雨云對象存儲的教程,對象存儲數據遷移教程

使用Rclone將阿里云對象存儲(OSS)的文件全部遷移至雨云對象存儲(ROS)的教程&#xff0c;其他的對象存儲也可以參照本教程。 Rclone簡介 Rclone 是一個用于和同步云平臺同步文件和目錄命令行工具。采用 Go 語言開發。 它允許在文件系統和云存儲服務之間或在多個云存儲服務之間…

STM32-EXTI外部中斷

目錄 一、中斷系統 二、STM32中斷 三、NVIC&#xff08;嵌套中斷向量控制器&#xff09;基本結構 四、NVIC優先級分組 五、EXTI外部中斷 5.1 外部中斷基本知識 5.2 外部中斷&#xff08;EXTI&#xff09;基本結構 ?編輯 5.2.1開發步驟&#xff1a; 5.3 AFIO復用IO口…

ADAudit Plus:強大的網絡安全衛士

隨著數字化時代的不斷發展&#xff0c;企業面臨著越來越復雜和多樣化的網絡安全威脅。在這個信息爆炸的時代&#xff0c;保護組織的敏感信息和確保網絡安全已經成為企業發展不可或缺的一環。為了更好地管理和監控網絡安全&#xff0c;ADAudit Plus應運而生&#xff0c;成為網絡…

ThreadLocal系列-ThreadLocalMap源碼

1.ThreadLocalMap.Entry key&#xff1a;指向key的是弱引用 value&#xff1a;強引用 public class ThreadLocal<T> {static class ThreadLocalMap {/*** The entries in this hash map extend WeakReference, using* its main ref field as the key (which is always…

32、卷積參數 - 長寬方向的公式推導

有了前面三節的卷積基礎 padding, stride, dilation 之后,大概就可以了解一個卷積算法的全貌了。 一個完整的卷積包含的輸入和輸出有: 輸入圖像,表示為[n, hi, wi, ci] 卷積核,表示為[co, kh, kw, ci] 輸出特征圖,表示為[n, ho, wo, co] 以上為卷積算法的兩個輸入 tensor…

【持更】python數據處理-學習筆記

1、讀取excel /csv及指定sheet&#xff1a; pd.read_excel("路徑",sheetname"xx") 修改列名df.rename 修改字符串類型到數字 pandas.to_numeric&#xff08;&#xff09; 2、刪除drop、去重drop_duplicates &#xff08;1&#xff09;空值所在行/列 行&am…

Redis分布式鎖有什么缺陷?

Redis分布式鎖有什么缺陷&#xff1f; Redis 分布式鎖不能解決超時的問題&#xff0c;分布式鎖有一個超時時間&#xff0c;程序的執行如果超出了鎖的超時時間就會出現問題。 1.Redis容易產生的幾個問題&#xff1a; 2.鎖未被釋放 3.B鎖被A鎖釋放了 4.數據庫事務超時 5.鎖過期了…

centos 7 卸載圖形化界面步驟記錄

centos7 服務器操作系統&#xff0c;挺小一配置&#xff0c;裝了圖形化界面&#xff0c;現在運行程序的時候跑不動了&#xff0c;我想這圖形界面也沒啥用&#xff0c;卸載了算了&#xff01; 卸載步驟 yum grouplist 查詢已經安裝的組件 可以看到 圖形化界面 等是以分組存在的…

深入理解Spring IOC的工作流程

理解Spring IOC&#xff08;Inversion of Control&#xff09;的工作流程是理解Spring框架的核心之一。下面是Spring IOC的基本工作流程&#xff1a; 配置&#xff1a; 開發者通過XML配置文件、Java配置類或者注解等方式&#xff0c;定義應用中的Bean以及它們之間的依賴關系。這…