实验11:装饰模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解装饰模式的动机,掌握该模式的结构;
2、能够利用装饰模式解决实际问题。
[实验任务]:手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
类图![](https://i-blog.csdnimg.cn/blog_migrate/cf4a1a7c23c54b6a6506613327de8e4a.png)
源代码
public interface Phone
{
//声音提醒
public void ring();
}
public final class SimplePhone implements Phone
{
public SimplePhone()
{
System.out.println("一部SimplePhone");
}
@Override
public void ring()
{
System.out.println("声音提醒");
}
}
public class JarPhone extends PhoneDecorator
{
public JarPhone(Phone phone)
{
super(phone);
System.out.println("一部JarPhone");
}
//震动提醒
public void shake()
{
System.out.println("震动提醒");
}
}
public class ComplexPhone extends PhoneDecorator
{
public ComplexPhone(Phone phone)
{
super(phone);
System.out.println("一部ComplexPhone");
}
//震动提醒
public void shake()
{
System.out.println("震动提醒");
}
//闪烁提醒
public void shine()
{
System.out.println("闪烁提醒");
}
}
public class PhoneDecorator implements Phone
{
private Phone phone;
public PhoneDecorator(Phone phone)
{
this.phone = phone;
}
@Override
public void ring()
{
phone.ring();
}
}
public class Client
{
public static void main(String[] args)
{
Phone phone;
//实例化SimplePhone
phone = new SimplePhone();
//声音提醒
phone.ring();
System.out.println("-------------");
//实例化JarPhone
JarPhone jarPhone = new JarPhone(phone);
//声音加震动提醒
jarPhone.ring();
jarPhone.shake();
System.out.println("-------------");
//实例化ComplexPhone
ComplexPhone complexPhone = new ComplexPhone(phone);
//声音加震动加闪烁提醒
complexPhone.ring();
complexPhone.shake();
complexPhone.shine();
}
}