用于循环依赖于上下文的输出的设计模式

时间:2014-04-10 14:58:52

标签: java design-patterns

我遇到了问题,我想知道是否有适用的已知模式。我在考虑访客,但我不确定。问题如下:让我们说我有一个可以使用不同颜色的盒子队列。

public class Box{
   public color;
   public Box(String color){
       this.color= color;
   }
   public print(boolean afterGreen){

         System.out.print("\n color is "+color);
         if (afterGreen)
            System.out.print("and goes after a green box");

   }
}

然后我有颜色队列

List<Box> queue = new ArrayList<Box>;
queue.add(new Box("red"));
queue.add(new Box("green"));
queue.add(new Box("blue"));
queue.add(new Box("green"));
queue.add(new Box("yellow"));

然后我要打印

boolean afterGreen = false;
for(Box box : queue){
    box.print(afterGreen);
    afterGreen = "green".equals(box.color);
}

如您所见,方法print()需要上下文信息。所以我在循环中计算它并将其作为参数传递给print()方法。

有没有更好的方法来做到这一点,所以我不必在循环中做到这一点?是否有解决此问题的设计模式?

2 个答案:

答案 0 :(得分:0)

我会这样做:

class Box {
    private String color;

    public Box(String color) {
        this.color = color;
    }

    public void printAfter(Box previousBox) {
        System.out.print("\n color is " + color);

        if (previousBox != null && previousBox.color.equals("green")) {
            System.out.print("and goes after a green box");
        }
    }
}

Box previousBox;
for(Box box : queue){
    box.printAfter(previousBox);
    previousBox = box;
}

关于绿色后打印的决定包含在Box对象中。

答案 1 :(得分:0)

你会考虑实现类似的东西。

boolean wasGreen = false;
for(Box box : queue) {
    box.print();
    if(wasGreen) {
        System.out.print("and goes after a green box");
    }
    wasGreen = "green".equals(box.color);
}
相关问题