public class HouseProject {
private final Set steps = new HashSet();
public HouseProject(Steps... steps) {
this.steps.addAll(Arrays.asList(steps));
}
public enum Steps {
CREATE_BASEMENT,
ADD_FLOOR,
CREATE_ROOF,
BUILD_FENCE
}
public Set getSteps() {
return steps;
}
}
public abstract class Builder {
protected Builder nextBuilder;
private final HouseProject.Steps step;
public Builder(HouseProject.Steps step) {
this.step = step;
}
public abstract void buildImpl();
public void build(HouseProject project) {
if (project.getSteps().contains(step)) {
buildImpl();
}
if (nextBuilder != null) {
nextBuilder.build(project);
}
}
public Builder setNext(Builder builder) {
nextBuilder = builder;
return builder;
}
}
public class BasementBuilder extends Builder {
public BasementBuilder() {
super(HouseProject.Steps.CREATE_BASEMENT);
}
@Override
public void buildImpl() {
System.out.println("Building basement");
}
}
public class FloorBuilder extends Builder {
public FloorBuilder() {
super(HouseProject.Steps.ADD_FLOOR);
}
@Override
public void buildImpl() {
System.out.println("Building floor");
}
}
public class RoofBuilder extends Builder {
public RoofBuilder() {
super(HouseProject.Steps.CREATE_ROOF);
}
@Override
public void buildImpl() {
System.out.println("Building roof");
}
}
public class FecneBuilder extends Builder {
public FecneBuilder() {
super(HouseProject.Steps.BUILD_FENCE);
}
@Override
public void buildImpl() {
System.out.println("Building fence");
}
}
public class Client {
public static void main(String[] args) {
Builder firstBuilder, lastBuilder;
firstBuilder = lastBuilder = new BasementBuilder();
lastBuilder = lastBuilder.setNext(new FloorBuilder())
.setNext(new RoofBuilder())
.setNext(new FecneBuilder());
HouseProject hp = new HouseProject(
HouseProject.Steps.CREATE_BASEMENT,
HouseProject.Steps.ADD_FLOOR,
HouseProject.Steps.CREATE_ROOF
);
firstBuilder.build(hp);
}
}
/**
* Output:
* Building basement
* Building floor
* Building roof
*/
среда, 14 марта 2012 г.
Паттерн Цепочка обязанностей(Chain of responsibility). Пример кода
Подписаться на:
Комментарии к сообщению (Atom)
Это же строитель, а не цепочка
ОтветитьУдалить