2014-05-11 05:29

题目链接

原题:

Design remote controller for me.

题目:设计一个遥控器。

解法:遥控什么?什么遥控?传统的红外线信号吗?我只能随便说说思路吧。不知道这算什么类型的面试题,真遇到的话也算是倒了霉了。想了半天恍然大悟:原来是考察设计模式。查了相关资料后发现命令模式比较符合题意,所以就依葫芦画瓢写了个例子。

代码:

 1 // http://www.careercup.com/question?id=6366101810184192
 2 interface ICommand {
 3     public abstract void execute();
 4 }
 5 
 6 public class PowerOnCommand implements ICommand {
 7     @Override
 8     public void execute() {
 9         // TODO Auto-generated method stub
10         System.out.println("Power on.");
11     }
12 
13 }
14 
15 public class PowerOffCommand implements ICommand {
16     @Override
17     public void execute() {
18         // TODO Auto-generated method stub
19         System.out.println("Power off.");
20     }
21 }
22 
23 import java.util.Vector;
24 
25 public class RemoteController {
26     private Vector<ICommand> buttons;
27     private String[] configuration = {"PowerOnCommand", "PowerOffCommand"};
28     
29     public RemoteController() {
30         // TODO Auto-generated constructor stub
31         buttons = new Vector<ICommand>();
32         for (String commandType : configuration) {
33             try {
34                 try {
35                     buttons.add((ICommand) Class.forName(commandType).newInstance());
36                 } catch (InstantiationException e) {
37                     // TODO Auto-generated catch block
38                     e.printStackTrace();
39                 } catch (IllegalAccessException e) {
40                     // TODO Auto-generated catch block
41                     e.printStackTrace();
42                 }
43             } catch (ClassNotFoundException e) {
44                 // TODO Auto-generated catch block
45                 e.printStackTrace();
46             }
47         }
48     }
49     
50     public void push(int commandIndex) {
51         try {
52             buttons.elementAt(commandIndex).execute();
53         } catch (ArrayIndexOutOfBoundsException e) {
54             // TODO: handle exception
55         }
56     }
57 }

 

 posted on 2014-05-11 05:34  zhuli19901106  阅读(181)  评论(0编辑  收藏  举报