装饰模式
1、理解装饰模式的动机,掌握该模式的结构;
2、能够利用装饰模式解决实际问题。
[实验任务]:手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;
而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
类图:
源代码:
Client类:
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();
}
}
Phone类:
public abstract class Phone {
public void serviceCall() {
}
}
SimplePhone类:
public class SimplePhone extends Phone {
public void serviceCall() {
System.out.println("SimplePhone:发出声音提醒主人电话来了");
}
}
PhoneDecoration类:
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();
}
}
JarPhone类:
public class JarPhone extends PhoneDecoration {
public JarPhone(Phone phone) {
super(phone);
// TODO 自动生成的构造函数存根
}
@Override
public void serviceCall() {
super.serviceCall();
System.out.println("JarPhone:发出声音并震动提醒主人电话来了");
}
}
ComplexPhone类:
public class ComplexPhone extends PhoneDecoration {
public ComplexPhone(Phone phone) {
super(phone);
// TODO 自动生成的构造函数存根
}
@Override
public void serviceCall() {
super.serviceCall();
System.out.println("ComplexPhone:发出声音、震动并灯光闪烁提醒主人电话来了");
}
}
标签:总结,11.09,phone,每日,System,Phone,serviceCall,println,public From: https://www.cnblogs.com/-GYP/p/17822812.html