【Java】【设计模式 Design Pattern】装饰器模式 Decorator

package cn.echo42.decorator;

/**
 * @author DaiZhiZhou
 * @file Netty
 * @create 2020-07-29 16:49
 */
public class Client {

    public static void main(String[] args) {
        Phone huaweiP30 = new Huawei();
        huaweiP30.function();
        System.out.println(huaweiP30.price());

        huaweiP30 = new MediaPlayerPhoneDecorator(huaweiP30);
        huaweiP30.function();
        System.out.println(huaweiP30.price());

        huaweiP30 = new ShotPhoneDecorator(huaweiP30);
        huaweiP30.function();
        System.out.println(huaweiP30.price());

        // 单件购买也可以
        Phone phone = new MediaPlayerPhoneDecorator();
        System.out.println(phone);
    }

    interface Phone {
        int price();
        void function();
    }

    static class Huawei implements Phone {
        @Override
        public int price() {
            return 1000;
        }

        @Override
        public void function() {
            System.out.println("华为手机的基础功能");
        }
    }

    interface PhoneDecorator extends Phone{

    }

    static class MediaPlayerPhoneDecorator implements PhoneDecorator {

        private Phone phone;

        public MediaPlayerPhoneDecorator() {
        }

        public MediaPlayerPhoneDecorator(Phone phone) {
            this.phone = phone;
        }

        public void setPhone(Phone phone) {
            this.phone = phone;
        }

        @Override
        public int price() {
            return 200 + this.phone.price();
        }

        @Override
        public void function() {
            phone.function();
            System.out.println("增强了MP3播放功能");
        }
    }

    static class ShotPhoneDecorator implements PhoneDecorator {

        private Phone phone;

        public ShotPhoneDecorator(Phone phone) {
            this.phone = phone;
        }


        public ShotPhoneDecorator() {
        }

        public void setPhone(Phone phone) {
            this.phone = phone;
        }

        @Override
        public int price() {
            return this.phone.price();
        }

        @Override
        public void function() {
            phone.function();
            System.out.println("增强了拍摄功能");
        }
    }
}

测试结果:

华为手机的基础功能
1000
华为手机的基础功能
增强了MP3播放功能
1200
华为手机的基础功能
增强了MP3播放功能
增强了拍摄功能
1200
cn.echo42.decorator.Client$MediaPlayerPhoneDecorator@677327b6

Process finished with exit code 0

猜你喜欢

转载自www.cnblogs.com/mindzone/p/13398416.html