本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解装饰模式的动机,掌握该模式的结构;
2、能够利用装饰模式解决实际问题。
[实验任务一]:手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
实验要求:
1.提交类图;
2.提交源代码;
3.注意编程规范。
1、类图
源代码
package org.example;
public class Changer implements Phone{
private Phone phone;
public Changer(Phone p) {
this.phone=p;
}
public void voice() {
phone.voice();
}
}
package org.example;
public class Client {
public static void main(String[] args) {
Phone phone;
phone=new SimplePhone();
phone.voice();
JarPhone jarphone=new JarPhone(phone);
jarphone.voice();
jarphone.zhendong();
ComplexPhone complexphone = new ComplexPhone(phone);
complexphone.zhendong();
complexphone.dengguang();
}
}
package org.example;
public class ComplexPhone extends Changer{
public ComplexPhone(Phone p) {
super(p);
System.out.println("ComplexPhone");
}
public void zhendong() {
System.out.println("会震动!");
}
public void dengguang() {
System.out.println("会发光!");
}
}
package org.example;
public class JarPhone extends Changer{
public JarPhone(Phone p) {
super(p);
System.out.println("Jarphone");
}
public void zhendong() {
System.out.println("会震动!");
}
}
package org.example;
public interface Phone {
public void voice();
}
package org.example;
public class SimplePhone implements Phone {
public void voice() {
System.out.println("发出声音!");
}
}
3、运行截图