资源描述:
《JAVA枚举与设计模式》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Java枚举与程序设计作者:李金峰枚举单例模式责任链模式1.1一个枚举的小例子packagecom.li;publicenumWeeKDay{MON,TUS,WED,THI,FRI,SAT,SUN;}1.2枚举概述关键字enum可以将一组具名的值的有限集合创作成一种新的类型,而这种具名的值可以作为常规的组件使用1.3基本函数valueOf();name();Ordinal();toString();1.4静态导入packagecom.li;importstaticcom.li.WeekDay1.*;publicclassTestStaticI
2、mport{publicstaticvoidmain(String[]args){System.out.println(MON);}}1.5.1向enum中添加新方法1publicenumWeekDay2{MON(1),TUS,WED,THI(4),FRI,SAT,SUN;privateintvalue;privateWeekDay2(){}privateWeekDay2(intvalue){this.value=value;}publicintgetValue(){returnthis.value;}}1.5.2向enum中添加新方法2pu
3、blicenumWeekDay3{MON("Monday"),TUS("Tuesday"),WED("Wednesday"),THI("Thursday"),FRI("Friday"),SAT("Saturday"),SUN("Sunday");privateStringweek;privateWeekDay3(Stringweek){this.week=week;}publicStringgetWeek(){returnthis.week;}}1.6覆盖toString()方法publicenumWeekDay5{MON,TUS,WED,T
4、HI,FRI,SAT,SUN;publicStringtoString(){returnname().toLowerCase();}}1.6实现publicenumWeekDay6implementsOperate{MON,TUS,WED,THI,FRI,SAT,SUN;@OverridepublicStringdoSomething(){//TODOAuto-generatedmethodstubreturnnull;}}1.7随机选取publicclassEnums{privatestaticRandomrand=newRandom(47
5、);publicstatic>Trandom(Classcl){returnrandom(cl.getEnumConstants());}publicstaticTrandom(T[]values){returnvalues[rand.nextInt(values.length)];}}枚举单例模式责任链模式2单例模式由于枚举的构造函数必须是私有的,所以用它实现单例模式非常简单。2.1单例实现1publicenumSingleton{INSTANCE;privateStringname;public
6、StringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicstaticvoidmain(String[]args){INSTANCE.setName("DS");System.out.println(INSTANCE.getName());}}2.2单例实现2publicenumSingleton1{RED(255,0,0),GREEN(0,255,0),BLUE(0,0,255);intredValue;intgreenValue;intb
7、lueValue;privateSingleton1(intred,intgreen,intblue){this.redValue=red;this.greenValue=green;this.blueValue=blue;}publicintgetRedValue(){returnredValue;}publicvoidsetRedValue(intred){this.redValue=red;}publicintgetGreenValue(){returngreenValue;}publicvoidsetGreenValue(intgre
8、en){this.greenValue=green;}publicintgetBlueValue(){returnblueValue;}publicvoidsetB