当前位置:网站首页>装饰器(一)

装饰器(一)

2020-11-08 21:03:49 8Years

//装饰器的具体应用;
//例如,把一个声音扩大2
// 实现过程:1.声音的接口,2.人这个类,3.扩音器这个类
// 4.把人这个类传进扩音器这个类来,从而实现声音的扩大(所以扩音器里面要有一个构造器(用来传入人这个对象))

public class testDerector {

    public static void main(String[] args) {
        Person p= new Person();

        p.say();

        Amplifile amplifile=new Amplifile(p);
        amplifile.say();

    }

    interface Say {
        void say();
    }


    public static class Person implements Say{


        private int voice=10;

        @Override
        public void say() {
            System.out.println(this.getVoice());

        }
        public int getVoice() {
            return voice;
        }
        public void setVoice(int voice) {
            this.voice = voice;
        }

    }

    static class Amplifile implements Say{

        private Person p;

        public Amplifile(Person p) {
            this.p = p;
        }
        @Override
        public void say() {
            System.out.println("扩音器"+p.getVoice()*2);
        }
    }
}

输出结果            10    扩音器20

版权声明
本文为[8Years]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4583813/blog/4708092