装饰模式
[实验任务一]:手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
实验要求:
1. 提交类图;
2. 提交源代码;
package DecoratorPattern;
/**
* 抽象手机构件类:抽象构件类
* @author gong
*
*/
abstract class Gj19CellPhone {
public abstract void receiveCall();
}
package DecoratorPattern;
/**
* 简单手机类:具体构件类
* @author gong
*
*/
public class Gj19SimplePhone extends Gj19CellPhone{
@Override
public void receiveCall() {
System.out.println("声音提示");
}
}
构件装饰类:抽象装饰类
package DecoratorPattern;
/**
* 构件装饰类:抽象装饰类
* @author gong
*
*/
public class Gj19PhoneDecorator extends Gj19CellPhone{
private Gj19CellPhone phone=null;
public Gj19PhoneDecorator(Gj19CellPhone phone) {
if(phone!=null){
this.phone = phone;
}else{
this.phone = new Gj19SimplePhone();
}
}
@Override
public void receiveCall() {
phone.receiveCall();
}
}
Jar手机类:具体装饰类
package DecoratorPattern;
/**
* Jar手机类:具体装饰类
* @author gong
*
*/
public class Gj19JarPhone extends Gj19PhoneDecorator{
public Gj19JarPhone(Gj19CellPhone phone) {
super(phone);
}
public void receiveCall() {
super.receiveCall();
System.out.println("震动提示");
}
}
Complex手机类:具体装饰类
package DecoratorPattern;
/**
* Complex手机类:具体装饰类
* @author gong
*
*/
public class Gj19ComplexPhone extends Gj19PhoneDecorator{
public Gj19ComplexPhone(Gj19CellPhone phone) {
super(phone);
}
public void receiveCall() {
super.receiveCall();
System.out.println("灯光闪烁提示");
}
}
客户端测试类
package DecoratorPattern;
/**
* 客户端测试类
* @author gong
public class Gj19client {
public static void main(String a[]){
Gj19CellPhone p1 = new Gj19SimplePhone();
p1.receiveCall();
System.out.println();
Gj19CellPhone p2 = new Gj19JarPhone(p1);
p2.receiveCall();
System.out.println();
Gj19CellPhone p3 = new Gj19ComplexPhone(p2);
p3.receiveCall();
}
}
3. 注意编程规范。