11.8
实验11:装饰模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解装饰模式的动机,掌握该模式的结构;
2、能够利用装饰模式解决实际问题。
[实验任务一]:手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
实验要求:
类图、
代码
1、Phone.java
package org.example.shiyanshiyi;
public interface Phone {
void ring();
}
2、SimplePhone.java
package org.example.shiyanshiyi;
public class SimplePhone implements Phone{
@Override
public void ring(){
System.out.println("手机响铃");
}
}
3、PhoneDector.java
package org.example.shiyanshiyi;
public abstract class PhoneDecorator implements Phone{
protected Phone phone;
public PhoneDecorator(Phone phone){
this.phone=phone;
}
@Override
public void ring(){
phone.ring();
}
}
4、JarPhone.java
package org.example.shiyanshiyi;
public class JarPhone extends PhoneDecorator{
public JarPhone(Phone phone){
super(phone);
}
@Override
public void ring(){
super.ring();
vibrate();
}
private void vibrate(){
System.out.println("手机振动");
}
}
5、ComplexPhone.java
package org.example.shiyanshiyi;
public class ComplexPhone extends PhoneDecorator{
public ComplexPhone(Phone phone){
super(phone);
}
@Override
public void ring(){
super.ring();
flashLight();
}
private void flashLight() {
System.out.println("手机灯光闪烁");
}
}
6、Client.java
package org.example.shiyanshiyi;
public class Client {
public static void main(String[] args) {
Phone simplePhone=new SimplePhone();
simplePhone.ring();
Phone jarPhone=new JarPhone(simplePhone);
jarPhone.ring();
Phone complexPhone=new ComplexPhone(jarPhone);
complexPhone.ring();
}
}
运行结果