书城计算机网络大话设计模式
8183300000102

第102章 3 房屋

大B:“这样吧,我给你举个使用构建房屋的场景来说明‘生成器’吧!首先,这是我们最终需要生成的产品――房屋,它具有房间数量和门数量的属性。”

package com。alex。designpattern。builder;

/***// *最终我们需要的产品――房屋

*/

public class House……{

int roomNumber;

int doorNumber;

public House()……{

roomNumber=0;

doorNumber=0;

}

public int getRoomNumber()……{

return roomNumber;

}

public int getDoorNumber()……{

return doorNumber;

}

}

大B:“接下来就是房屋的真正构建者――‘生成器’的接口定义,以及它的一个实现。”

package com。alex。designpattern。builder;

/***// *房屋构建者的接口

*

*/

public interface HouseBuilder……{

public void BuildRoom(int roomNo);

public void BuildDoor(int room1,int room2);

public House getHouse();

}

package com。alex。designpattern。builder;

public class ConcreteHouseBuilderA implements HouseBuilder……{

private House house;

public ConcreteHouseBuilderA()……{

house=new House();

}

public void BuildRoom(int roomNo)……{

//you can create a new Room added to a House

house。roomNumber=house。roomNumber roomNo;

}

public void BuildDoor(int room1,int room2)……{

//you can create a new door assotiated with 2 room//and added this door into a house

house。doorNumber=house。doorNumber room1 room2;

}

public House getHouse()……{

return house;

}

}

大B:“这就是所谓的Director――最终构建房屋的‘表示者’。我们需要给它提供‘生成器’,然后由它来构建房屋。”package com。alex。designpattern。builder;

/***// *房屋(构建)的“表示”者,通过它我们可以对同一种构建采用不同的表示方式

*

*/

public class HouseDirector……{

public static House CreateHouse(HouseBuilder concreteBuilder)……{

concreteBuilder。BuildRoom(1);

concreteBuilder。BuildRoom(2);

concreteBuilder。BuildDoor(1,2);

concreteBuilder。BuildDoor(2,1);

return concreteBuilder。getHouse();

}

}

大B:“最后,当然是我们的测试启动类了,可以看到,使用生成器模式的简单过程就是:1、创建生成器对象。2、表示者使用此生成器对象构建最终产品。”

package com。alex。designpattern。builder;

/***// *A test client to create a house《br》

*but we do not know how the room and door be created

*《p》

*

*Builder(生成器模式)

*《p》

*将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

*/

public class Test……{

public static void main(String[]args)……{

ConcreteHouseBuilderA myHouseBuilder=new ConcreteHouseBuilderA();

House myHouse=HouseDirector。CreateHouse(myHouseBuilder);

System。out。println(My house has room: myHouse。getRoomNumber());

System。out。println(My house has door: myHouse。getDoorNumber());

}

}