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

上一篇:设计模式(10):JAVA(10):设计模式(3)工厂模式:提供了一种创建对象的最佳方式(3)抽象工厂


下一篇:设计模式之装饰者模式