一、练习题

1. 咖啡店的咖啡可以供客人们饮用,还会满足客人们加奶和加糖的要求,但是需要收费,如:冰咖啡:30元,美式咖啡35元,奶:6元,糖:4元,请用装饰模式模拟设计一个程序,实现输出每种饮料的详情和总价格(咖啡价格 + 配料价格)。

类图

核心代码

package DesignPattern.decorator

public abstract class Coffee {
    public Coffee(private let price: Int64) {}

    public func show(): Unit

    public func getmoney(): Int64
}


public open class Batch <: Coffee {
    public Batch(private let coffee: Coffee, private let price: Int64){
        super(price)
    }

    public open override func show() {
        coffee.show()
    }

    public override func getmoney() {
        return coffee.getmoney() + price
    }
}

public class Milk <: Batch {
    public Milk(private let coffee: Coffee, private let price: Int64){
        super(coffee, price)
    }

    public override func show() {
        super.show()
        this.addMilk()
    }

    private func addMilk() {
        print("牛奶 ")
    }
}

public class Sugger <: Batch {
    public Sugger(private let coffee: Coffee, private let price: Int64){
        super(coffee, price)
    }

    public override func show() {
        super.show()
        this.addSugger()
    }

    private func addSugger() {
        print("白糖 ")
    }
}

public class IcedCoffee <: Coffee {
    public IcedCoffee(private let price: Int64) {
        super(price)
    }

    public override func show() {
        print("冰咖啡 ")
    }

    public override func getmoney() {
        return price
    }
}

public class AmericanCoffee <: Coffee {
    public AmericanCoffee(private let price: Int64) {
        super(price)
    }

    public override func show() {
        print("美式咖啡 ")
    }

    public override func getmoney() {
        return price
    }
}

测试代码

package DesignPattern
import DesignPattern.decorator.*

main(): Int64 {
    let coffee = IcedCoffee(30)
    let milk = Milk(coffee, 6)
    let sugger = Sugger(milk, 4)
    sugger.show()
    println(sugger.getmoney())

    return 0
}

二、小结

本章为大家详细的介绍了仓颉设计模式中装饰模式练习题的内容,下一章,为大家带来外观模式的内容。最后,创作不易,如果大家觉得我的文章对学习仓颉设计模式有帮助的话,就动动小手,点个免费的赞吧!收到的赞越多,我的创作动力也会越大哦,谢谢大家🌹🌹🌹!!!

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐