实验任务
-
任务一:设计实现发声接口
-
List item
实验内容
任务一:设计实现发声接口
任务目的:
理解并掌握如何定义接口
掌握接口的实现方式
任务描述:
设计和实现一个Soundable接口,该接口具有发声功能,同时还能调节声音大小Soundable接口的这些功能将由有3种声音设备来实现他们分别是Radio、Walkman、Mobilephone。最后还需设计一个应用程序类来使用这些实现Soundable接口的声音设备。程序运行时,先询问用户想听那个设备,然后程序按照该设备的工作方式来输出发音。
实施步骤:
1. 定义 Soundable接口
public interface Soundable {
// 发出声音
public void playSound() ;
// 降低声音
public void decreaseVolume();
// 停止声音
public void stopSound();
}
2. 设计Radio类
public class Radio implements Soundable{
@Override
public void playSound() {
System.out.println("收音机播放广播:中央人民广播电视台。");
}
@Override
public void decreaseVolume() {
System.out.println("降低收音机音量。");
}
@Override
public void stopSound() {
System.out.println("关闭收音机。");
}
}
3. 设计Walkman类
public class Walkman implements Soundable{
@Override
public void playSound() {
System.out.println("随身听发出音乐");
}
@Override
public void decreaseVolume() {
System.out.println("降低随身听音量");
}
@Override
public void stopSound() {
System.out.println("关闭随身听");
}
}
4. 设计MobilePhone类
public class MobilePhone implements Soundable{
@Override
public void playSound() {
System.out.println("手机发出来电铃声:叮当 、 叮当");
}
@Override
public void decreaseVolume() {
System.out.println("降低手机音量");
}
@Override
public void stopSound() {
System.out.println("关闭手机");
}
}
5. 设计SampleDisplay类
class SampleDisplay {
public void display(Soundable soundable) {
soundable.playSound();
soundable.decreaseVolume();
soundable.stopSound();
}
}
6. 测试类
import java.util.Scanner;
public class TestDemo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("你想听什么?请输入:");
System.out.println("0-收音机 1-随身听 2-手机");
int choice;
choice = in.nextInt();
SampleDisplay sampledisplay = new SampleDisplay();
if (choice == 0)
sampledisplay.display(new Radio());
else if(choice == 1)
sampledisplay.display(new Walkman());
else if(choice == 2)
sampledisplay.display(new MobilePhone());
else
System.out.println("瓜娃,你输错了!");
in.close();
}
}