設計模式之Builder——購機篇
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
最近想買一臺電腦用於學習,因此我就去了一家電腦公司,經過分析,選用了下面的配置:
CPU P2.4
主板 Intel
硬盤 80G
。。。
買過電腦的朋友可能都知道,我們選好配置後,電腦公司就會有專門的組裝師(Assembler)來給我們裝機。電腦(Computer)就是由這些東西(我們稱之爲Part)組成的。學過經濟學的朋友可能都知道,如果這臺組裝好的電腦不賣掉,那它就不是商品(Commodity),而僅僅是臺電腦而已。
1、 在這裏,我們先定義商品(Commodity)類:
public class Commodity {
String commodity ="";
public Commodity (Part partA,Part partB,Part partC) {//由各個部分組成
this. commodity = partA.part+"/n";
this. commodity = product+partB.part+"/n";
this. commodity = product+partC.part;
System.out.println("我的機器配置爲:/n"+ commodity);
}
}
2、 下來我們再定義電腦的組成部分(Part)類:
public class Part {
String part="";
public Part(String part){
this.part = part;
}
}
3、 我們把電腦(Computer)定義成一個接口類:
public interface Computer {
//組裝部件A 比如CPU
void buildPartA();
//組裝部件B 比如主板
void buildPartB();
//組裝部件C 比如硬盤
void buildPartC();
//返回最後組裝成品結果 (返回最後組裝好的電腦)
//成品的組裝過程不在這裏進行,而是由組裝師(Assembler)類完成的。
//從而實現了過程和部件的分離
Commodity getCommodity();
}
4、 定義電腦的組裝師(Assembler)類:
public class Assembler {
private Computer computer;
public Assembler(Computer computer) { //主要任務是裝電腦
this.computer = computer;
}
// 將部件partA partB partC最後組成複雜對象
//這裏是將主板、CPU和硬盤組裝成PC的過程
public void construct() {
computer.buildPartA();
computer.buildPartB();
computer.buildPartC();
}
}
5、 我的電腦是對電腦(Computer)接口的具體實現,因此再定義MyComputer實現類:
public class MyComputer implements Computer {
Part partA, partB, partC;
public void buildPartA() {
partA = new Part("P42.4 CPU");
}
public void buildPartB() {
partB = new Part("Inter 主板");
}
public void buildPartC() {
partC = new Part("80G硬盤");
}
public Commodity getCommodity() {
//返回最後組裝成品結果
Commodity myComputer = new Commodity (partA,partB,partC);
return myComputer;
}
}
6、 編寫測試類:
public class MyComputerTest {
public static void main(String args[]){
MyComputer myComputer = new MyComputer(); //組裝我的電腦
Assembler assembler = new Assembler( myComputer ); //派某一位組裝師
assembler.construct(); //組裝師進行組裝過程
Commodity commodity = myComputer.getCommodity(); //賣給我的電腦(商品)
}
}
7、說明:
A:代碼只用來學習Builder模式,要運行的話,必須要做一點改動。
B:將一個複雜對象的構建與它的表示分離,使得同樣的構建過程可以創建不同的表示。因爲每個人的電腦配置可能都是不同的。
C:我們使用Builer是爲了構建複雜對象的過程和它的部件解耦,也就是說將過程分的儘可能細,而且每一部分只用完成自己的功能即可(各司其職嘛)。
8、特別感謝:
感謝LevinLee網友提出的意見,出現你所說的問題是由於調試程序是用的是Product類,後來爲說明問題改成Commodity 類,有些地方忘了改過來,就出現了你說的那種情況。我以改正過來了,錯誤之處希望大家指正。在此感謝!