我作了一個練習,以組裝電腦的觀念設計一builder pattern,builder pattern的特別的地方是適用在建構複雜的物件,builder可以有很多種,也方便替換builder。client不需要知道product細節。
Client:
買電腦
Director:
pcBuilder = new PcBuilder()
if "miniPC" then
pc = miniPcBuilder.setCase("XPC shuttle Z95")
.setCPU("Intel i7 7900k")
.setMem("Apacer DDR4 2400 32GB")
.setDPcard("Nvidia 1050 Ti")
.setMonitor("BenQ 24")
.setKeyboard("Microsoft natural KB+mouse")
.build()
if "genPC" then
pc = PcBuilder.setCase("酷碼 CM 690 III(網孔版)")
.setPower("be quiet! E10-600W 80+金牌")
.setMB("華碩 X99-DELUXE/U3.1")
.setCPU("Intel I7-5820K")
.setMem("美光 8G*4 DDR4-2400")
.setDPcard("EVGA GTX750TI 2GB")
.setMonitor("ASUS 24")
.setKeyboard("羅技 MK200")
.setMouse("羅技M3000")
.build()
return pc
PcBuilder:
pc = new PC();
setCase(case)
pc.case = case
return this
setPower(power)
pc.power = power
return this
setMB(MB)
pc.MB = MB
return this
setCPU(CPU)
pc.CPU = CPU
return this
setMem(Mem)
pc.Mem = Mem
return this
setDPcard(DPcard)
pc.DPcard = DPcard
return this
setMonitor(Monitor)
pc.Monitor = Monitor
return this
setKeyboard(Keyboard)
pc.Keyboard = Keyboard
return this
setMouse(Mouse)
pc.Mouse = Mouse
return this
build()
return pc
miniPcBuilder extend PcBuilder:
pc = new PC();
setCase(case)
pc.case = case
return this
setCPU(CPU)
check_CPU_fit_the_case()
pc.CPU = CPU
return this
setMem(Mem)
check_MEM_fit_the_case()
pc.Mem = Mem
return this
setDPcard(DPcard)
check_DPcard_fit_the_case()
pc.DPcard = DPcard
return this
setMonitor(Monitor)
check_Monitor_fit_the_DPcard()
pc.Monitor = Monitor
return this
setKeyboard(Keyboard)
pc.Keyboard = Keyboard
return this
setMouse(Mouse)
pc.Mouse = Mouse
return this
build()
return pc
PC:
case
power
MB
CPU
Mem
DPcard
Monitor
Keyboard
沒有留言:
張貼留言