(7-9)请根据提示补全程序空白处,使程序能够正确运行。①Action{//定义接口voidsay();}classPerson{privateStringname;publicPerson(Stringname){this.name=name;}publicvoidaddListener(②){action.say();}}publicclassDemo14{publicstaticvoidmain(String[]args){newPerson("孙悟空").addListener(③{publicvoid④{System.out.println("八戒,前方妖气很重,保护好师傅!");}});}}
(7-9)请根据提示补全程序空白处,使程序能够正确运行。//JDK8下的接口定义interfaceMyInterface{voidshow();//抽象方法//静态方法①voidprint(){System.out.println("print");}//默认方法②voidreceive(){System.out.println("receive");}}publicclassMyClass③MyInterface{publicvoidshow(){System.out.println("show");}}publicclassDemo{publicstaticvoidmain(String[]args){MyClassc=newMyClass();c.show();c.receive();④;//调用MyInterface的print()方法}}
(7-16)根据提示补全程序空白处,使程序能够正确运行。//利用适配器模式,把一个英文单词翻译成中文//源类:英语单词类classEnglish{privateString[]list={"dream","great","wonderful"};publicString①{returnlist[i];}publicintgetSize(){returnlist.length;}}//目标接口:汉语interface②{String③;}//适配器类,把英语单词转换成中文class④implementsChinese{private⑤list;intindex;publicPowerAdapter(Englishlist,intindex){this.list=list;this.index=index;}publicStringgetChinese(){//把英文转换成中文if(this.index>list.getSize()||this.index<0)returnnull;Stringword=list.getEnglishWord(this.index);if(word.equalsIgnoreCase("dream"))return"梦想";elseif(word.equalsIgnoreCase("great"))return"伟大";elseif(word.equalsIgnoreCase("wonderful"))return"绝妙的";returnnull;}}publicclassDemoAdapter{publicstaticvoidmain(String[]args){Englishenglish=newEnglish();Chinesechinese=newPowerAdapter(english,0);System.out.println(chinese.getChinese());}}
(7-16)根据提示补全程序空白处,使程序能够正确运行。//观察者模式案例:教师授课,学生听课//老师接口publicinterfaceITeacher{publicvoidaddStudent(IStudentstudent);//增加学生publicvoiddeleteStudent(IStudentstudent);//移除学生publicvoid①(Stringcontent);//讲授知识}//学生接口publicinterfaceIStudent{publicvoid②(Stringcontent);//学生听课}//老师类publicclassTeacherimplementsITeacher{//利用Vector保存所有的学生privateVector<③>studentList=newVector<>();privateStringname;//教师名publicTeacher(Stringname){this.name=name;}publicvoidaddStudent(IStudentstudent){this.studentList.add(student);}publicvoiddeleteStudent(IStudentstudent){this.studentList.remove(student);}//遍历老师的学生,告诉学生老师上课了publicvoidteaching(Stringcontent){System.out.println(this.name+"正在讲授:"+content+"\n");//老师给所有学生上课for(IStudentstudent:④){StringBuffersb=newStringBuffer();sb.append(((Student)student).getName()+"已经了解了"+content);System.out.println(sb.toString());}}}//学生类publicclassStudentimplementsIStudent{privateStringname;publicStudent(StringstudentName){this.name=studentName;}publicStringgetName(){returnname;}publicvoidlistening(Stringcontent){//学生在听课System.out.println(content);}}//测试类publicclassDemo{publicstaticvoidmain(String[]args){ITeacherts=newTeacher("唐僧");//产生一个老师IStudentswk=newStudent("孙悟空");//产生3个学生IStudentzbj=newStudent("猪八戒");IStudentshs=newStudent("沙和尚");//把学生加入到老师的课堂ts.addStudent(swk);ts.addStudent(zbj);ts.addStudent(shs);//老师开始上课ts.teaching("大乘佛教三藏真经");⑤;//猪八戒上课开小车,被唐僧赶出教室ts.teaching("徒弟们,现在吃东西");}}