用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
类图:
源码:
1. 提交源代码;
package simplePhone;
/**
* 抽象手机构件类:抽象构件类
* @author 9986
*
*/
public abstract class Phone {
public abstract void voice();
}
package simplePhone;
/**
* 简单手机类:具体构件类
* @author 9986
*
*/
public class SimplePhone extends Phone{
public SimplePhone() {
System.out.println("这是一部简单手机");
}
@Override
public void voice() {
System.out.println("手机来电声音");
}
}
package simplePhone;
/**
* 构件装饰类:抽象装饰类
* @author 9986
*
*/
public class Changer extends Phone{
private Phone phone;
public Changer(Phone phone) {
this.phone=phone;
}
@Override
public void voice() {
phone.voice();
}
}
package simplePhone;
/**
* Complex手机类:具体装饰类
* @author 9986
*
*/
public class ComplexPhone extends Changer{
public ComplexPhone(Phone phone) {
super(phone);
System.out.println("变成高级手机");
flash();
}
public void flash() {
System.out.println("手机来电闪烁灯光提示");
}
}
package simplePhone;
/**
* Jar手机类:具体装饰类
* @author 9986
*
*/
public final class JarPhone extends Changer{
public JarPhone(Phone phone) {
super(phone);
System.out.println("手机增加震动功能");
}
public void voice() {
super.voice();
System.out.println("来电震动");
}
}
package simplePhone;
/**
* 客户端测试类
* @author 9986
*
*/
public class Client {
public static void main(String[] args) {
//父类调用子类方法
Phone p1=new SimplePhone();
p1.voice();
System.out.println("====================");
Phone p2=new JarPhone(p1);
p2.voice();
System.out.println("====================");
Phone p3=new ComplexPhone(p2);
p3.voice();
}
}
标签:phone,实现,System,模式,public,Phone,println,voice,装饰 From: https://www.cnblogs.com/222wan/p/17818979.html