软件设计 石家庄铁道大学信息学院
实验11:装饰模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解装饰模式的动机,掌握该模式的结构;
2、能够利用装饰模式解决实际问题。
[实验任务一]:手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
实验要求:
1. 提交类图;
2. 提交源代码;
Client.java
package ruanshe11;
public class Client {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Phone p1 = new SimplePhone();
System.out.println("生产简单手机");
p1.serviceCall();
System.out.println("***********************");
Phone p2 = new JarPhone(p1);
System.out.println("升级手机为JarPhone");
p2.serviceCall();
System.out.println("***********************");
Phone p3 = new ComplexPhone(p2);
System.out.println("升级手机为ComplexPhone");
p3.serviceCall();
}
}
ComplexPhone.java
package ruanshe11;
public class ComplexPhone extends PhoneDecoration {
public ComplexPhone(Phone phone) {
super(phone);
// TODO 自动生成的构造函数存根
}
@Override
public void serviceCall() {
super.serviceCall();
System.out.println("ComplexPhone:发出声音、震动并灯光闪烁,电话来了");
}
}
JarPhone.java
package ruanshe11;
public class JarPhone extends PhoneDecoration {
public JarPhone(Phone phone) {
super(phone);
// TODO 自动生成的构造函数存根
}
@Override
public void serviceCall() {
super.serviceCall();
System.out.println("JarPhone:发出声音并震动,电话来了");
}
}
Phone.java
package ruanshe11;
public abstract class Phone {
public void serviceCall() {
}
}
PhoneDecoration.java
package ruanshe11;
public class PhoneDecoration extends Phone {
private Phone phone=null;
public PhoneDecoration(Phone phone) {
if(phone!=null){
this.phone = phone;
}else{
this.phone = new SimplePhone();
}
}
@Override
public void serviceCall() {
phone.serviceCall();
}
}
SimplePhone.java
package ruanshe11;
public class SimplePhone extends Phone {
public void serviceCall() {
System.out.println("SimplePhone:发出声音,电话来了");
}
}
3.注意编程规范。