2
我有這個計劃,我認爲它代表了一種生成器模式,但我有這個擔心,我不明白從戈夫其代表性的獨立建築。如何在構建器模式中將構造分離出來?
這裏是代碼,
public class IDMaker {
public static void main(String[] args) {
...
IDDirector director = new IDDirector();
IDBuilder idB;
switch(role){
case 'a': {
idB = new StudentIDBuilder(idnumber, fname, lname);
break;
}
case 'b': {
idB = new FacultyIDBuilder(idnumber, fname, lname);
break;
}
default: {
idB = new StudentIDBuilder(idnumber, fname, lname);
break;
}
}
director.MakeID(idB);
ID id = idB.getID();
...
}
}
這是導演類的程序。
public class IDDirector {
public void MakeID(IDBuilder idB){
idB.addIDNumber();
idB.addName();
idB.addWidth();
idB.addHeight();
}
}
這是該程序的抽象生成器。
abstract class IDBuilder{
public abstract void addIDNumber();
public abstract void addName();
public abstract void addWidth();
public abstract void addHeight();
public abstract ID getID();
}
這是該計劃的具體建設者之一。
class StudentIDBuilder extends IDBuilder{
String idnumber;
String fname;
String lname;
int width = 180;
int height = 300;
StudentIDBuilder(String idnumber, String fname,String lname){
this.idnumber=idnumber;
this.fname=fname;
this.lname=lname;
}
private ID id = new ID();
public void addIDNumber(){id.idnumber = this.idnumber;}
public void addName(){id.fname = this.fname;id.lname = this.lname;}
public void addWidth(){id.width = this.width;}
public void addHeight(){id.height = this.height;}
public ID getID(){return id;}
}
這是該程序的產物。
class ID{
public String idnumber;
public String fname;
public String lname;
public int width;
public int height;
public String getIDNumber(){return this.idnumber;}
public String getName(){return this.lname + ", " + fname;}
public String getSize(){return width + "x" + height;}
}
構建模式在這個程序中是否正確使用?對於不同的表示
它不是一個生成器模式,看看這個http://www.javaworld.com/article/2074938/core-java/too-many-parameters-in-java-methods-part-3-builder- pattern.html –