thinking in java -第11章持有对象-练习27

queue 的练习

Command类

 1 package collection.test;
 2 
 3 public class Command {
 4     private String word;
 5 
 6     public Command(String word) {
 7         this.word = word;
 8     }
 9 
10     public String getWord() {
11         return word;
12     }
13 
14     public void operation() {
15         System.out.println(getWord());
16     }
17 
18 }

使用Command对象填充queue

 1 package collection.test;
 2 
 3 import java.util.Queue;
 4 
 5 public class QueueFill {
 6 
 7     public Command fill(Command command, Queue<Command> queue) {
 8         queue.offer(command);
 9         return command;
10     }
11 
12 }

消耗掉queue里的对象

 1 package collection.test;
 2 
 3 import java.util.Queue;
 4 
 5 public class Consumer {
 6 
 7     public void consumer(Queue<Command> queue) {
 8         queue.peek().operation();
 9         queue.remove();
10     }
11 
12 }

test

 1 package collection.test;
 2 
 3 import java.util.LinkedList;
 4 import java.util.Queue;
 5 
 6 public class TestQueue {
 7     public static void main(String[] args) {
 8         QueueFill queueFill = new QueueFill();
 9         Queue<Command> queue = new LinkedList<Command>();
10         Consumer consumer = new Consumer();
11         for (int i = 0; i < 10; i++) {
12             queueFill.fill(new Command("word" + i), queue);
13 
14         }
15         for (int i = 0; i < 10; i++) {
16             consumer.consumer(queue);
17         }
18     }
19 }
posted @ 2012-08-26 20:07  sunnyfan  阅读(199)  评论(0)    收藏  举报