Java设计模式之Builder 模式

builder 设计模式中,如果某个product没有实现builder的全部操作,应该把具体实现者设置为抽象类,但是后续主函数中的代码就遇到了问题,抽象的具体实现者这给类不能被实例化,Director调用不了builder

求解决!!

1个回答

**interface PersonBuilder {

void buildHead();

void buildBody();

void buildFoot();

Person buildPerson();

}

class ManBuilder implements PersonBuilder {

Person person;

public ManBuilder() {

person = new Person();

}

public void buildBody() {

person.setBody("建造身体");

}

public void buildFoot() {  
    person.setFoot("建造脚");  
}  

public void buildHead() {  
    person.setHead("建造头");  
}  

public Person buildPerson() {  
    return person;  
}  

}

class PersonDirector {

public Person constructPerson(PersonBuilder pb) {  
    pb.buildHead();  
    pb.buildBody();  
    pb.buildFoot();  
    return pb.buildPerson();  
}  

}

class Person {

private String head;

private String body;

private String foot;

public String getHead() {  
    return head;  
}  

public void setHead(String head) {  
    this.head = head;  
}  

public String getBody() {  
    return body;  
}  

public void setBody(String body) {  
    this.body = body;  
}  

public String getFoot() {  
    return foot;  
}  

public void setFoot(String foot) {  
    this.foot = foot;  
}  

}

public class Client {

public static void main(String[] args) {

PersonDirector pd = new PersonDirector();

Person person = pd.constructPerson(new ManBuilder());

System.out.println(person.getBody());

System.out.println(person.getFoot());

System.out.println(person.getHead());

}

}

**

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐