装饰者模式

一、文件目录

装饰者模式

二、继承关系图

装饰者模式

三、代码

Beverage.jva

package decoratormode.interfa;

public abstract class Beverage {
    protected String description = "Unknown Beverage";
    public abstract double cost();
    public String getDescription(){
        return description;
    } //这里的描述不是抽象的,正是因为它本身实现了
}

CondimentDecorator.java

package decoratormode.interfa;

public abstract class CondimentDecorator extends Beverage{
    public abstract String getDescription();//所有的调料装饰者都必须重新实现
}

Espresso.java

package decoratormode.impl;

import decoratormode.interfa.Beverage;

public class Espresso extends Beverage {

    public Espresso(){
        description = "Espresso";
    }
    @Override
    public double cost() {
        return 1.99;
    }
}

HouseBlend.java

package decoratormode.impl;

import decoratormode.interfa.Beverage;

public class HouseBlend extends Beverage {

    public HouseBlend(){
        description = "House Blend Coffee";
    }
    @Override
    public double cost() {
        return .89;
    }
}

Mocha.java

package decoratormode.impl;

import decoratormode.interfa.Beverage;
import decoratormode.interfa.CondimentDecorator;

public class Mocha extends CondimentDecorator {
    Beverage beverage;

    public Mocha(Beverage beverage){
        this.beverage = beverage;
    }

    @Override
    public double cost() {
        return .20 + beverage.cost();
    }

    @Override
    public String getDescription() {
        return beverage.getDescription() + ", Mocha";
    }
}

Mai.java

package decoratormode;

import decoratormode.impl.Espresso;
import decoratormode.impl.HouseBlend;
import decoratormode.impl.Mocha;
import decoratormode.interfa.Beverage;

public class Mai {
    public static void main(String[] args) {
        Beverage beverage = new Espresso();
        System.out.println(beverage.getDescription() + " $" +beverage.cost());
        Beverage beverage2 = new HouseBlend();
        beverage2 = new Mocha(beverage2);
        beverage2 = new Mocha(beverage2);
        System.out.println(beverage2.getDescription() + "$ " + beverage2.cost());
    }
}

四、输出
Espresso $1.99
House Blend Coffee, Mocha, Mocha$ 1.29

Process finished with exit code 0
 

上一篇:如何在Visual Studio Code中用Mocha对TypeScript进行测试


下一篇:javascript-使用Mocha和requirejs进行测试