建造者模式詳解及實戰案例分析

2021-10-06 18:18:37 字數 2658 閱讀 4757

建造者模式和工廠模式區別?

錯誤示範

框架中的建造者模式

建造者模式又稱:構建者模式,builder 模式 屬於建立型

假設有這樣一道設計面試題:我們需要定義乙個資源池配置類 resourcepoolconfig

成員變數

解釋是否必填

預設值name

資源名稱是無

maxtotal

最大資源數量否8

maxidle

最大空閒資源數量否8

minidle

最小空閒資源數量否0

public

class

resourcepoolconfig

this

.name = name;

if(maxtotal != null)

this

.maxtotal = maxtotal;}if

(maxidle != null)

this

.maxidle = maxidle;}if

(minidle != null)

this

.minidle = minidle;}}

//...省略getter方法...

}

以上思路暴露的問題

這裡你可能想到那麼用set不就可以了麼?

// 只展示改動的**

public

class

resourcepoolconfig

this

.name = name;

}// 使用set方式

public

void

setmaxidle

(int maxidle)

this

.maxidle = maxidle;

}// ... 依次類推 set*(...)

}// 使用

resourcepoolconfig config =

newresourcepoolconfig

("dbconnectionpool");

config.

setmaxtotal(16

);config.

setmaxidle(8

);

以上思路暴露的問題

package com.warape.designpattern.builder;

import org.apache.commons.lang3.stringutils;

public

class

resourcepoolconfig

public

static

class

builder

if(maxidle > maxtotal)

if(minidle > maxtotal || minidle > maxidle)

return

newresourcepoolconfig

(this);

}public builder setname

(string name)

this

.name = name;

return

this;}

public builder setmaxtotal

(int maxtotal)

this

.maxtotal = maxtotal;

return

this;}

public builder setmaxidle

(int maxidle)

this

.maxidle = maxidle;

return

this;}

public builder setminidle

(int minidle)

this

.minidle = minidle;

return

this;}

}}// 使用

resourcepoolconfig config =

newresourcepoolconfig.builder()

.setname

("dbconnectionpool").

setmaxtotal(16

).setmaxidle(10

).setminidle(12

).build()

;

網上有乙個經典的例子很好地解釋了兩者的區別。

顧客走進一家餐館點餐,我們利用工廠模式,根據使用者不同的選擇,來製作不同的食物,比

如披薩、漢堡、沙拉。對於披薩來說,使用者又有各種配料可以定製,比如乳酪、西紅柿、起

司,我們通過建造者模式根據使用者選擇的不同配料來製作披薩。

大家都用過lombok,以下**是我在實際開發中見到過有人這麼寫的

@data

@builder

@allargsconstructor

@noargsconstructor

public

class

user

有沒有發現user有雙重身份。他又是標準bean,又是建造者模式。不建議這麼使用。

建造者模式案例

private string food 食物private string drink 飲料public string getfood public void setfood string food public string getdrink public void setdrink string ...

詳解設計模式 建造者模式

建造者模式 builder 將乙個複雜的構建與其表示相分離,使得同樣的構建過程可以建立不同的表示。主要解決在軟體系統中,有時候面臨著 乙個複雜物件 的建立工作,由於需求的變化,這個複雜物件的某些部分經常面臨著劇烈的變化,一些基本部件不會變。所以需要將變與不變分離。與抽象工廠的區別 在建造者模式裡,有...

設計模式詳解之建造者模式

建造者模式屬於建立型模式,提供了一種建立物件的最佳方式。定義 將乙個複雜物件的構建與它的表示分離,使得同樣的構建過程可以建立不同的表示。主要作用 在使用者不知道物件的建造過程和細節的情況下就可以直接建立複雜的物件。product產品類 通常是實現了模板方法模式 這裡可以後續看我的更新部落格,如果我更...