对部分乐器进行建模,其类图如图所示,包括,乐器( Instrument)、管乐器(wind)、打击乐器( Percussion)、弦乐器( Stringed)、木管乐器( Woodwind)、铜管乐器( Brass)。
下面是实现上述设计的Java代码,其中音乐类( Music)使用各类乐器( Instrument)进行演奏和调音等操作。
enum Note{/*枚举各种音调*/
MIDDLE_C, C_SHARP, B_FLAT;//其他略
}
interface Instrument{/*接口,乐器*/
__(1)__;//p1ay方法接口
void adjust();// adjust方法接口
}
class Wind __(2)__{
public void play(Note n){System. out. println("Wind. play() "+ n);}
public void adjust(){System. out. println("Wind. adjust ()");}
}
/*类 Percussion和 Stringed实现代码略*/
class Brass __(3)__{
public void play(Note n){System. out. println("Brass. play()"+ n);}
public void adjust(){System. out. println("Brass. adjust ()");}
}
class Woodwind extends Wind{
public void play(Note n){System. out. printin("Woodwind. play()"+ n);}
}
public class Music{
void tune(Instrument i){i.play(Note. MIDDLE_C);}
void adjust(Instrument i){i.adjust();}
void tuneAll(__(4)__ e){
for(Instrument i : e){
adjust(i);
tune (i);
}
}
public static void main(String[] args){
Music music=__(5)__ Music();
Instrument[] orchestra =I new Wind(), new Woodwind ()};
music. tuneAll(orchestra);
}
}
Wind. adjust ()
Wind. play () MIDDLE_C
Wind. adjust()
Woodwind. play() MIDDLE_C