11章-练习27


import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

/**
* 练习27: 写一个称为Command的类,它包括一个String域和一个显示该String的operation()方法。
* 写第二个类,它具有一个使用Command对象来填充一个Queue并返回这个对象的方法。
* 将填充后的Queue传递给第三个类的一个方法,该方法消耗掉Queue中的对象,并调用它们的operation()方法.
*/
public class Excrcise27 {

public static void main(String[] args) {

Random random = new Random(47);
Queue<Command> queue = null;
for (int i = 0; i < 10; i++) {
Command command = new Command(random.nextInt(100) + "-" + i);
queue = SecondClass.operation(command);
}
ThirdClass.operation(queue);

}
}

class ThirdClass {

public static void operation(Queue<Command> queue) {

while (queue != null & queue.peek() != null) {
Command c = queue.remove();
c.operation();
}
System.out.println("消费完了 : " + queue);
}

}

class SecondClass {

private static Queue<Command> queue = new LinkedList<Command>();

public static Queue operation(Command command) {

queue.offer(command);
return queue;
}

}

class Command {
private String str;

public Command(String str) {
this.str = str;
}

public void operation() {
System.out.println("str :" + str);
}
}
/* Output:
str :58-0
str :55-1
str :93-2
str :61-3
str :61-4
str :29-5
str :68-6
str :0-7
str :22-8
str :7-9
消费完了 : []
*///:~
posted @ 2022-08-25 18:19  loadL  阅读(17)  评论(0)    收藏  举报