实验11:装饰模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解装饰模式的动机,掌握该模式的结构;
2、能够利用装饰模式解决实际问题。
[实验任务一]:手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
实验要求:
1. 提交类图;
2.提交源代码;
// 基础手机接口
public interface Phone {
void receiveCall();
}
// 简单手机实现
public class SimplePhone implements Phone {
@Override
public void receiveCall() {
System.out.println("Receiving call: Sound alert");
}
}
// 装饰器基类
public abstract class PhoneDecorator implements Phone {
protected Phone phone;
public PhoneDecorator(Phone phone) {
this.phone = phone;
}
@Override
public void receiveCall() {
if (phone != null) {
phone.receiveCall();
}
}
}
// 振动装饰器
public class VibrationDecorator extends PhoneDecorator {
public VibrationDecorator(Phone phone) {
super(phone);
}
@Override
public void receiveCall() {
super.receiveCall();
vibrate();
}
private void vibrate() {
System.out.println("Vibration alert");
}
}
// 灯光装饰器
public class LightDecorator extends PhoneDecorator {
public LightDecorator(Phone phone) {
super(phone);
}
@Override
public void receiveCall() {
super.receiveCall();
flashLight();
}
private void flashLight() {
System.out.println("Flashing light alert");
}
}
// 主方法测试
public class Main {
public static void main(String[] args) {
Phone simplePhone = new SimplePhone();
simplePhone.receiveCall();
Phone jarPhone = new VibrationDecorator(simplePhone);
jarPhone.receiveCall();
Phone complexPhone = new LightDecorator(jarPhone);
complexPhone.receiveCall();
}
}
3.注意编程规范。