看《java编程思想》时候做一道练习题,发现自己面向对象理解的很差....
题目如下:
写一个Command的类,它包含一个String域和一个显示该String的operator()方法.写第二个类,它具有Command对象来填充一个Queue并返回这个对象的方法.将填充后的Queue传递给第三个类的一个方法,该方法消耗Queue中的对象,并调用operator()方法.
Write a class called Command that contains a String and has a method operation() that displays the String. Write a second class with a method that fills a Queue with Command objects and returns it. Pass the filled Queue to a method in a third class that consumes the objects in the Queue and calls their operation() methods.
队列常被用作一种可靠的将对象从程序的某一区域传输到另一区域.在并发编程里面特别重要.
我写的(没写完还,反面案例.....)
class Command{ private String name; public Command(String name){ this.name = name; } public String operation(){ return this.name; } } class CommandQueue { public Queue<Command> addObject(Command cmd){ que.offer(cmd); return que; } } class CommondQueueO{ public void delete(){ } }
标准答案:
class Command{ private final String cmd; Command(String cmd){ this.cmd = cmd; } void operator(){ System.out.println(cmd); } } class Producer{ public static void produce(Queue<Command> q){ q.offer(new Command("load")); q.offer(new Command("delete")); q.offer(new Command("save")); q.offer(new Command("exit")); } } class Consumer{ public static void consume(Queue<Command> q){ while(q.peek() != null){ q.remove().operator(); } } } public class Ext_27_ { public static void main(String[] args) { // TODO Auto-generated method stub Queue<Command> cmds = new LinkedList<Command>(); Producer.produce(cmds); Consumer.consume(cmds); } }
或者:
class Command { String s; Command(String s) { this.s = s; } void operation() { System.out.print(s); } } class Build { Queue<Command> makeQ() { Queue<Command> q = new LinkedList<Command>(); for(int i = 0; i < 10; i++){ q.offer(new Command(i + " ")); } return q; } } public class Ext_27_1 { public static void commandEater(Queue<Command> qc) { while(qc.peek() != null) qc.poll().operation(); } public static void main(String[] args) { Build b = new Build(); commandEater(b.makeQ()); } }
哎.......人家写的这才叫程序....
-----------------------------------------------------
转载请注明来源此处
原地址:#
发表