建造者模式

建造者模式大致是这样工作的,有一个实体类,比如生产电视机,里面有属性:显像管,外壳,电路板...  有一个方法类,里面包括各种组合电视的方法:做零件,焊接,组合... 还有一个控制流程的类, 它负责流程的控制,比如先做零件,再焊接,最后组合。
现在你知道怎样使用建造者模式来生产电视机了吧。

实现代码:
package Builder;

public class TestClient  {
    public TestClient() {
    }

    public static void main(String[] args) {
        House myHouse = new House();
        
        ConcreteHouseBuilderA myHouseBuilder = new ConcreteHouseBuilderA();
        HouseDirector myHouseDirector = new HouseDirector();
        myHouseDirector.CreateHouse(myHouseBuilder);
        myHouse = myHouseBuilder.getHouse();

        System.out.println("My house has room :" + myHouse.getRoomNumber());
        System.out.println("My house has door :" + myHouse.getDoorNumber());
    }
}


package Builder;

public class ConcreteHouseBuilderA  extends 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++;
    }

    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++;
    }

    public House getHouse() {
        return house;
    }
}


package Builder;

public abstract class HouseBuilder  {
    public abstract void BuildRoom(int roomNo);
    public abstract void BuildDoor(int room1, int room2);
    public abstract House getHouse();
}


package Builder;

public class HouseDirector  {
    public void CreateHouse(HouseBuilder concreteBuilder) {
        concreteBuilder.BuildRoom(1);
        concreteBuilder.BuildRoom(2);
        concreteBuilder.BuildDoor(1, 2);

        //return builder.getHouse();
    }
}


你可能感兴趣的:(java,工作)