随笔- 509  文章- 0  评论- 151  阅读- 22万 

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   zhuli19901106  阅读(181)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示