适配器模式允许您在适配器中包装其他不兼容的对象,以使其与另一个类兼容。
示例:语言学习,绝大多数人学习英语,日语系的同学要学日语
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Student { void studyEnglish(); } class NormalStudent extend Student{ public void studyEnglish(){ // study } public void studyJapanese(){ // no } } class JapaneseStudent extend Student{ public void studyEnglish(){ // no } public void studyJapanese(){ // study } } class StudentAdapter { public void study(NormalStudent student){ if(student instanceof NormalStudent){ student.studyEnglish(); } if(student instanceof JapaneseStudent){ student.studyJapanese(); } } } class User{ StudentAdapter adapter = new StudentAdapter(); adapter.study(new NormalStudent()); adapter.study(new JapaneseStudent()); //... }
|