相关问题
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
类图实现
具体代码
//Phone.java
package org.example.test010;
public interface Phone {
public void promote();
}
//SimplePhone.java
package org.example.test010;
public final class SimplePhone implements Phone {
public SimplePhone() {
System.out.println("是一部简单手机~");
}
@Override
public void promote() {
System.out.println("在接收来电时,会发出声音提醒~");
}
}
//UpGrade.java
package org.example.test010;
public class UpGrade implements Phone {
private Phone phone;
public UpGrade(Phone phone) {
this.phone = phone;
}
@Override
public void promote() {
phone.promote();
}
}
//JarPhone.java
package org.example.test010;
public class JarPhone extends UpGrade {
public JarPhone(Phone phone) {
super(phone);
System.out.println("变成一部可震动手机~");
}
public void promote() {
System.out.println("接收来电时,可发出声音,也可震动~");
}
}
//ComplexPhone.java
package org.example.test010;
public class ComplexPhone extends UpGrade {
public ComplexPhone(Phone phone) {
super(phone);
System.out.println("变成一部更高级的手机~");
}
public void promote() {
System.out.println("接收来电时,可发出声音,可震动,也可灯光闪烁提示~");
}
}
//Main.java
package org.example.test010;
public class Main {
public static void main(String[] args) {
Phone phone;
phone = new SimplePhone();
phone.promote();
System.out.println("-------------------------");
JarPhone jarPhone = new JarPhone(phone);
jarPhone.promote();
System.out.println("-------------------------");
ComplexPhone complexPhone = new ComplexPhone(phone);
complexPhone.promote();
}
}
运行结果