刚刚和大峡讨论一个问题,接口编程,这个话题也许大家比我理解多了,我提出一个自己的观点:在个人程序中空接口很少,至少我见的很少!大峡:不对,空接口很多,接口只不过是一个标识,然后我们做了一个很有意思的程序:
空接口,标识宇宙中万事万物:
public interface SomeThing {}
人类的接口:
public interface Humans extends SomeThing {}
动物的接口:
public interface Animals extends SomeThing {}
然后是一系列的实现:
中国人:
public class Chinese implements Humans {}
日本人:
public class Japanese {}
狗:
public class Dog implements Animals {}
妖怪(他很聪明,给自己帖上了人的标签):
public class Monster implements Humans {}
这个系统中的重点,猎人类及他的智能猎枪:
public class Hunter {
//智能的枪
public void intelligent(Object target)
{
if(target instanceof Animals){
System.out.println("打死了一个动物");
}
else if(target instanceof Humans)
{
System.out.println("这个是人类不能开枪的!");
return;
}else {
System.out.println("打死一个日本人,它竟然连动物都不是,浪费了一颗子弹,唉!");}
//下面进行秒杀等相关处理
//销毁他
target=null;
}
public static void main(String[] args) {
Hunter hunter=new Hunter();
Object[] objects=new Object[]{new Dog(),new Chinese(),new Japanese(),new Monster()};
for(int i=0;i<objects.length;i++)
hunter.intelligent(objects[i]);
}
};
这个程序都是通过一系列的空接口来实现的,不过最后他使用一个内部类,要不new 接口就出错了,程序简单,设计颇见优雅,值得大家学习,最后输出结果是:
打死一个动物!
这个是人类不能开枪的!
打死一个日本人,它竟然连动物都不是,浪费一颗子弹,唉!
这个是人类不能开枪!
这个例子就是为了说明接口编程的优雅,否定了传统了"编程一般不创建空接口",其实接口不过是个标识而已,采用内部类一样可以和普通类一样使用,而且更有他的独到之处,本例中的妖怪就是一个典型,他给自己贴上人的标签猎人的智能枪就不认识了,而日本人就很傻,连人的标志都不知道给自己贴上,企有不死之理!哈哈