问题描述
packageChapter14_RTTI;publicinterfaceFactory<T>{Tcreate();}
packageChapter14_RTTI;importjava.util.ArrayList;importjava.util.List;importjava.util.Random;publicclassPart{@OverridepublicStringtoString(){returnthis.getClass().getSimpleName();}staticList<Factory<?extendsPart>>partFactories=newArrayList<Factory<?extendsPart>>();static{partFactories.add(newFuelFilter.Factory());/**继续添加类型,,,省去,*/}privatestaticRandomrandom=newRandom(47);publicstaticPartcreatRandom(){returnpartFactories.get(random.nextInt(partFactories.size())).create();}}classFilterextendsPart{}classFuelFilterextendsFilter{publicstaticclassFactoryimplementsChapter14_RTTI.Factory<FuelFilter>{@OverridepublicFuelFiltercreate(){returnnewFuelFilter();}}}classFuelFilterSextendsFuelFilter{publicstaticclassFactoryimplementsChapter14_RTTI.Factory<FuelFilterS>{@OverridepublicFuelFilterScreate(){returnnewFuelFilterS();}}}classAirFilterextendsFilter{publicstaticclassFactoryimplementsChapter14_RTTI.Factory<AirFilter>{@OverridepublicAirFiltercreate(){returnnewAirFilter();}}}classOilFilterextendsFilter{publicstaticclassFactoryimplementsChapter14_RTTI.Factory<OilFilter>{@OverridepublicOilFiltercreate(){returnnewOilFilter();}}}classBeltextendsPart{}classFanBeltextendsBelt{publicstaticclassFactoryimplementsChapter14_RTTI.Factory<FanBelt>{@OverridepublicFanBeltcreate(){returnnewFanBelt();}}}classGeneratorBeltextendsBelt{publicstaticclassFactoryimplementsChapter14_RTTI.Factory<GeneratorBelt>{@OverridepublicGeneratorBeltcreate(){returnnewGeneratorBelt();}}}classPowerSteeringBeltextendsBelt{publicstaticclassFactoryimplementsChapter14_RTTI.Factory<PowerSteeringBelt>{@OverridepublicPowerSteeringBeltcreate(){returnnewPowerSteeringBelt();}}}
packageChapter14_RTTI;publicclassTest{publicstaticvoidmain(String[]args){for(inti=0;i<10;i++)System.out.println(Part.creatRandom());}}
输出FuelFilterFuelFilterFuelFilterFuelFilterFuelFilterFuelFilterFuelFilterFuelFilterFuelFilterFuelFilter
这个显得有点高深,懂得可以谈谈,其实这个例子是联系上文的,但是凭借我的理解还是不能够,对注册工厂或者是工厂方法或者《thinkinginjava》有一定理解的同学可以谈谈!!!
解决方案
解决方案二:
这是很常见的一种设计模式,如果java语言还不是很好可以先忽略这些。我是菜鸟,我说我的理解。给你举个例子吧,要做一个加减乘除最简单的俩数计算。a+b或者a-b那么可以定义一个接口publicinterfaceOperator(){publicdoublegetResult(doublea,doubleb);}
然后你的加减乘除都实现这个接口,classplusimplementsOperator{doublea;doubleb;plus(doublea,doubleb){this.a=a;this.b=b;}publicdoublegetResult(doublea,doubleb){returna+b;}}
减法,乘法,除法只用写类就行。这样有什么好处呢?就是说,你现在有main函数,写好的,调用接口中的方法,不用考虑具体是哪个类,到时候根据你传入的类名就能得到想要的结果。又有一个原则:扩展开放,修改关闭。所以这么写就能直接增加功能但不修改代码。也就是面向接口的编程模式。具体你用反射加配置文件就能实现外部控制程序执行。减小耦合度,减小依赖程度。所谓轻量级。
解决方案三:
这个例子是把一个比较简单的问题搞复杂了,你可以先抛开泛型,先了解一下什么是工厂模式。理解了工厂模式的工作机制之后,然后再看看泛型相关的,然后再看这个例子。
解决方案四:
在下看thinkinjava的时候java还没有泛型T_T