其中Cellphone为抽象类,声明了来电方法receiveCall(),Phone具体构件 为手机类,提供了声音提示,ConcreteDecorator1和ConcreteDecorator2分别提供了振动提示和灯光闪烁提示。DecoratorPhone是抽象装饰者,它维持一个对父类对象的引用。ConcreteDecorator1和ConcreteDecorator2是具体装饰者。
public interface Cellphone {
void receiveCall();
}
public class Phone implements Cellphone{
@Override
public void receiveCall() {
System.out.println("声音提示");
}
}
public class DecoratorPhone implements Cellphone{
private Cellphone cellphone=null;
public DecoratorPhone(Cellphone cellphone){
if(cellphone==null){
this.cellphone=cellphone;
}else {
this.cellphone=new Phone();
}
}
@Override
public void receiveCall() {
cellphone.receiveCall();
}
}
public class ConcreteDecorator1 extends DecoratorPhone{
public ConcreteDecorator1(Cellphone cellphone) {
super(cellphone);
}
@Override
public void receiveCall() {
super.receiveCall();
System.out.println("振动提示");
}
}
public class ConcreteDecorator2 extends DecoratorPhone{
public ConcreteDecorator2(Cellphone cellphone) {
super(cellphone);
}
@Override
public void receiveCall() {
super.receiveCall();
System.out.println("灯光闪烁提示");
}
}
package decoratorPattern;
public class Client {
public static void main(String[] args) {
Cellphone c1=new Phone();
c1.receiveCall(); //声音提示
Cellphone c2=new ConcreteDecorator1(c1);
c2.receiveCall(); //声音、震动提示
Cellphone c3=new ConcreteDecorator2(c1);
c3.receiveCall(); //声音、灯光
}
}
运行结果: