11.24

 

用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。

实验要求:

1.提交类图;

2.提交源代码;

3.注意编程规范。

 

 

类图:

 

 

 

源代码(Java实现):

 

public class Changer implements Phone{

 

    private Phone phone;

    public Changer(Phone p) {

        this.phone=p;

    }

    public void voice() {

        phone.voice();

    }

}

 

public class ComplexPhone extends Changer{

 

    public ComplexPhone(Phone p) {

        super(p);

        System.out.println("ComplexPhone");

    }

 

    public void zhendong() {

        System.out.println("会震动!");

    }

    public void dengguang() {

        System.out.println("会发光!");

    }

 

}

 

 

public class JarPhone extends Changer{

 

    public JarPhone(Phone p) {

        super(p);

        System.out.println("Jarphone");

    }

 

    public void zhendong() {

        System.out.println("会震动!");

    }

}

 

public interface Phone {

    public void voice();

}

 

public class SimplePhone implements Phone{

 

     public void voice() {

            System.out.println("发出声音!");

        }

 

}

 

public class Client {

    public static void main(String[] args) {

        Phone phone;

        phone=new SimplePhone();

        phone.voice();

        JarPhone jarphone=new JarPhone(phone);

        jarphone.voice();

        jarphone.zhendong();

        ComplexPhone complexphone = new ComplexPhone(phone);

        complexphone.zhendong();

        complexphone.dengguang();

    }

}

 

 

运行截图:

 

 

 

 

posted on 2024-11-24 21:46  HA_wind  阅读(1)  评论(0编辑  收藏  举报

导航