软件设计:实验11:装饰模式

实验11:装饰模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容: 

1、理解装饰模式的动机,掌握该模式的结构;

2、能够利用装饰模式解决实际问题。

 

[实验任务一]:手机功能的升级

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

实验要求:

1.提交类图;

2.提交源代码;

3.注意编程规范。

1.

.

2.// 抽象手机组件

abstract class Phone {

    protected Component component;

 

    public Phone(Component component) {

        this.component = component;

    }

 

    public abstract void ring();

}

 

// 具体手机组件

class SimplePhone extends Phone {

    public SimplePhone(Component component) {

        super(component);

    }

 

    @Override

    public void ring() {

        System.out.println("SimplePhone: Ringing...");

    }

}

 

// 抽象装饰者

abstract class Decorator extends Phone {

    public Decorator(Component component) {

        super(component);

    }

 

    @Override

    public void ring() {

        component.ring();

    }

}

 

// 具体装饰者1:振动功能

class VibrateDecorator extends Decorator {

    public VibrateDecorator(Component component) {

        super(component);

    }

 

    @Override

    public void ring() {

        super.ring();

        System.out.println("VibrateDecorator: Vibrating...");

    }

}

 

// 具体装饰者2:闪光灯功能

class FlashDecorator extends Decorator {

    public FlashDecorator(Component component) {

        super(component);

    }

 

    @Override

    public void ring() {

        super.ring();

        System.out.println("FlashDecorator: Flashing...");

    }

}

 

// 客户端代码

public class DecoratorPatternDemo {

    public static void main(String[] args) {

        Component simplePhone = new SimplePhone(null);

        simplePhone.ring(); // SimplePhone: Ringing...

 

        Component jarPhone = new VibrateDecorator(simplePhone);

        jarPhone.ring(); // SimplePhone: Ringing... + VibrateDecorator: Vibrating...

 

        Component complexPhone = new FlashDecorator(new VibrateDecorator(simplePhone));

        complexPhone.ring(); // SimplePhone: Ringing... + VibrateDecorator: Vibrating... + FlashDecorator: Flashing...

    }

}

posted @ 2024-11-28 21:03  痛苦代码源  阅读(1)  评论(0编辑  收藏  举报