IO装饰器

2021/5/22 10:30:24

本文主要是介绍IO装饰器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.扩音器

package com.sxt.io;

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

        Amplifier am =new Amplifier(p);
        am.say();
    }

}
interface Say{
    void say();
}
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;
    }
}
class Amplifier implements Say{
    private Person p;
    Amplifier(Person p){
        this.p=p;
    }
    @Override
    public void say() {
        System.out.println("人的声音为"+p.getVoice()*100);
        System.out.println("噪音");

    }
}

2.咖啡

package com.sxt.io;
/*
*模拟咖啡
* 1.抽象组件:需要装饰的抽象对象(接口或抽象父类)
* 2.具体组件:需要装饰的对象
* 3.抽象装饰类:包含了对抽象组件的引用以及装饰着共有的方法
* 4.具体装饰类:被装饰的对象
 */
public class DecorateTest02 {
    public static void main(String[] args) {
        Drink coffee =new Coffee();
        Drink suger =new Suger(coffee);
        System.out.println(suger.info()+"-->"+suger.cost());
        Drink milk =new Milk(coffee);
        System.out.println(milk.info()+"-->"+milk.cost());
    }
}
//抽象组件
interface Drink{
    double cost();//费用
    String info();//说明
}

//具体组件
class Coffee implements Drink{
    private String name="原味咖啡";
    @Override
    public double cost() {
        return 10;
    }

    @Override
    public String info() {
        return name;
    }
}
//抽象装饰类
abstract class Decorate implements Drink{
    //对抽象组件的引用
    private Drink drink;
    public Decorate( Drink drink){
        this.drink=drink;
    }
    @Override
    public double cost() {
        return this.drink.cost();
    }

    @Override
    public String info() {
        return this.drink.info();
    }
}

//具体装饰类
class Milk extends Decorate{

    public Milk(Drink drink) {
        super(drink);
    }
    @Override
    public double cost() {
        return super.cost()*4;
    }

    @Override
    public String info() {
        return super.info()+"加入了牛奶";
    }
}
class Suger extends Decorate{

    public Suger(Drink drink) {
        super(drink);
    }
    @Override
    public double cost() {
        return super.cost()*2;
    }

    @Override
    public String info() {
        return super.info()+"加入了蔗糖";
    }
}

原味咖啡加入了蔗糖-->20.0
原味咖啡加入了牛奶-->40.0



这篇关于IO装饰器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程