设计和实现一-个Soundable发声接口,该接口具有发声功能,同时还能调节声音大小。Soundable接口的这些功能将由有3种声音设备来实现,他们分别是收音机Radio、随身听Walkman、手机MobilePhone.最后还需设计--个应用程序类来使用这些实现Soundable接口的声音设备。程序运行时,先询问用户想哪个设备,用户选择设备后,程序按照该设备的工作方式打印发出的发音。
此案例分为五个类 Phone Radio Usersound WalkMan Test 一个接口Soundable
Soundable接口
public interface Soundable {public abstract void playSound();public abstract void lower();public abstract void stop();
}
Phone 类
public class Phone implements Soundable {@Overridepublic void playSound() {System.out.println("手机发出来电铃声:叮当 叮当");}@Overridepublic void lower() {System.out.println("以降低手机音量");}@Overridepublic void stop() {System.out.println("已关闭手机");}
}
Radio 类
public class Radio implements Soundable {@Overridepublic void playSound() {System.out.println("收音机播放广播:第八套小学生广播体操");}@Overridepublic void lower() {System.out.println("以降低收音机音量");}@Overridepublic void stop() {System.out.println("已关闭收音机");}
}
Usersound类
import java.util.Scanner;public class UserSound {public void use(Soundable s){s.playSound();System.out.println("是否降低音量? 1-是 2-否");Scanner sc =new Scanner(System.in);int a =sc.nextInt();if (a==1){s.lower();System.out.println("是否要关机?1-是 2-否");int b =sc.nextInt();if (b==1){s.stop();}}}
}
WalkMan 类
public class WalkMan implements Soundable{@Overridepublic void playSound() {System.out.println("正在播放歌曲;七里香");}@Overridepublic void lower() {System.out.println("以降低随身听音量");}@Overridepublic void stop() {System.out.println("已关闭随身听");}
}
Test类
import java.util.Scanner;public class Test {public static void main(String[] args) {System.out.println("你想听什么?请输入");System.out.println("0-收音机 1-随身听 2-手机");Scanner sc =new Scanner(System.in);int i= sc.nextInt();UserSound u=new UserSound();if (i==0){u.use(new Radio());}else if (i==1){u.use(new WalkMan());}else if (i==2){u.use(new Phone());}else{System.out.println("输入的有误");}}
}
结果展示