Careercup - Microsoft面试题 - 6314866323226624

时间:2023-03-09 00:18:22
Careercup - Microsoft面试题 - 6314866323226624

2014-05-11 05:29

题目链接

原题:

Design remote controller for me.

题目:设计一个遥控器。

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

代码:

 // http://www.careercup.com/question?id=6366101810184192
interface ICommand {
public abstract void execute();
} public class PowerOnCommand implements ICommand {
@Override
public void execute() {
// TODO Auto-generated method stub
System.out.println("Power on.");
} } public class PowerOffCommand implements ICommand {
@Override
public void execute() {
// TODO Auto-generated method stub
System.out.println("Power off.");
}
} import java.util.Vector; public class RemoteController {
private Vector<ICommand> buttons;
private String[] configuration = {"PowerOnCommand", "PowerOffCommand"}; public RemoteController() {
// TODO Auto-generated constructor stub
buttons = new Vector<ICommand>();
for (String commandType : configuration) {
try {
try {
buttons.add((ICommand) Class.forName(commandType).newInstance());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} public void push(int commandIndex) {
try {
buttons.elementAt(commandIndex).execute();
} catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
}
}
}