[实验任务一]:手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
1.提交类图;
2.提交源代码
Changer.java
package ornament;
public class Changer extends Phone{
private Phone phone;
public Changer(Phone phone) {
this.phone=phone;
}
@Override
public void voice() {
phone.voice();
}
}
Client.java
package ornament;
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();
}
}
ComolexPhone.java
package ornament;
public class ComplexPhone extends Changer{
public ComplexPhone(Phone phone) {
super(phone);
System.out.println("变成高级手机");
}
public void flash(){
System.out.println("手机来电闪烁");
}
}
JarPhone.java
package ornament;
public final class JarPhone extends Changer{
public JarPhone(Phone phone) {
super(phone);
System.out.println("增加震动功能");
}
public void voice() {
super.voice();
System.out.println("来电震动");
}
}
Phone.java
package ornament;
public abstract class Phone{
public abstract void voice();
}
SimplePhone.java
package ornament;
public class SimplePhone extends Phone {
public SimplePhone() {
System.out.println("这是一部简单手机");
}
@Override
public void voice() {
System.out.println("手机来电发出声音!");
}
}
标签:phone,System,模式,public,Phone,println,voice,装饰
From: https://www.cnblogs.com/yzx-sir/p/17851825.html