构建过程可以创建不同的表示。图 5-1 所示为其类图。 【 C++ 代 码 】
#include
using namespace std; class Product { private:
string partA, partB; public:
Product(){ }
void setPartA(const string&s){ PartA=s;} void setPartB(const string&s){ PartB=s;} ∥其余代码省略 }; class
Builder{ public: (1);
virtual void buildPartB()=0;
(2);
};
class ConcreteBuilder1: public Builder{ private:
Product* product; public:
ConcreteBuilder1(){product=new Product(); } void buildPartA(){ (3)(\ void buildPartB(){ (4)(\ Product*getResult(){ return product;} ∥其余代码省略 };
class ConcreteBuilder2: public Builder{ /*代码省略*/ };
class Director { private:
Builder* builder; public:
Director(Builder*pBuilder){builder*pBuilder;} void construct(){ (5)
∥其余代码省略 }
∥其余代码省略 };
int main(){
Director* director1=new Director(new ConcreteBuilder1()); directorl->construct(); delete director 1; return 0; }
试题六(共 15 分)
阅读下列说明和 Java 代码,将应填入(n)处的字句写在答题纸的对应栏内。
【说明】
生成器( Builder)模式的意图是将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。图 6-1 所示为其类图。
【Java 代码】
import java.util.*; class Product {
private String part A; private String part B; public Product(){}
public void setPartA(String s){ partA=s;} public void setPartB(String s){ partB=s;} }
interface Builder{ public (1);
public void buildPartB(); public (2); }
class ConcreteBuilder1: implements Builder{
private Product product;
public ConcreteBuilder1(){product=new Product(); } public void buildPartA(){ (3)(\ public void buildPartB(){ (4)(\ public Product getResult(){ return product;} }
class ConcreteBuilder2 implements Builder{ ∥代码省略 }
class Director {
private Builder builder;
public Director(Builder builder){this.builder=builder;} public void construct(){ (5)
∥代码省略 } }
class Test{
public static void main(String[]args){
Director director1=new Director(new ConcreteBuilder1()); directorl.construct(); } }