1
0
Fork 0

实现装饰器模式示例,添加相关类和方法,增强代码可读性

This commit is contained in:
IvisTang 2026-01-01 00:41:28 +08:00
parent 29fd3f0557
commit 443e4f2352
3 changed files with 164 additions and 0 deletions

66
go/decorator/main.go Normal file
View File

@ -0,0 +1,66 @@
package main
import "fmt"
/*
实例
汤宝宝家有一台咖啡机他会自动给美式咖啡加奶和糖...
*/
type Drink interface {
GetPrice() float64
cost()
}
type Coffee struct {
name string
Price float64
}
func (c *Coffee) GetPrice() float64 {
return c.Price
}
func (c *Coffee) cost() {
fmt.Printf("一杯%s咖啡价格%.2f元。\n", c.name, c.Price)
}
type Maker struct {
wrappedDrink Drink
milkPrice float64
sugarPrice float64
}
func (m *Maker) GetPrice() float64 {
return m.wrappedDrink.GetPrice()
}
func (m *Maker) cost() {
m.wrappedDrink.cost()
fmt.Printf("加了奶和糖,总价%.2f元。\n",
m.wrappedDrink.GetPrice()+m.milkPrice+m.sugarPrice)
}
func main() {
fmt.Println("============= 装饰器模式 =============")
var coffee, newCoffee Drink
fmt.Println("自己泡杯咖啡")
coffee = &Coffee{
name: "美式",
Price: 10.0,
}
coffee.cost()
fmt.Println("\n用咖啡机泡杯咖啡")
newCoffee = &Maker{
wrappedDrink: coffee,
milkPrice: 1.0,
sugarPrice: 1.0,
}
newCoffee.cost()
fmt.Println()
fmt.Println("=========== 装饰器模式结束 ===========")
}

48
python/decorator/main.py Normal file
View File

@ -0,0 +1,48 @@
"""
实例
汤宝宝家有一台咖啡机他会自动给美式咖啡加奶和糖...
"""
from abc import ABC, abstractmethod
class Drink(ABC):
price: float
name: str
@abstractmethod
def cost(self) -> None:
pass
class Coffee(Drink):
def __init__(self, name: str, price: float) -> None:
self.name = name
self.price = price
def cost(self) -> None:
print(f"一杯{self.name}咖啡,价格{self.price:.2f}")
class Maker:
def __init__(self, drink: Drink, milk_price: float, sugar_price: float) -> None:
self.drink = drink
self.milk_price = milk_price
self.sugar_price = sugar_price
def cost(self) -> None:
self.drink.cost()
print(
f"加了奶和糖,总价{self.drink.price + self.milk_price + self.sugar_price:.2f}元。"
)
if __name__ == "__main__":
print("============= 装饰器模式 =============")
print("自己泡杯咖啡")
coffee = Coffee("美式", 10.0)
coffee.cost()
print("\n用咖啡机泡杯咖啡")
new_coffee = Maker(coffee, milk_price=1.0, sugar_price=1.0)
new_coffee.cost()
print("\n=========== 装饰器模式结束 ===========")

50
ts/src/decorator/index.ts Normal file
View File

@ -0,0 +1,50 @@
/*
...
*/
interface Drink {
price: number;
name: string;
cost(): void;
}
class Coffee implements Drink {
price: number;
name: string;
constructor(name: string, price: number) {
this.name = name;
this.price = price;
}
cost() {
console.log(`一杯${this.name}咖啡,价格${this.price.toFixed(2)}`);
}
}
class Maker {
drink: Drink;
milkPrice: number;
sugarPrice: number;
constructor(drink: Drink, milkPrice: number, sugarPrice: number) {
this.drink = drink;
this.milkPrice = milkPrice;
this.sugarPrice = sugarPrice;
}
cost() {
this.drink.cost();
const total = this.drink.price + this.milkPrice + this.sugarPrice;
console.log(`加奶加糖后,总价${total.toFixed(2)}`);
}
}
(function(){
console.log("============= 装饰器模式 =============");
console.log("自己泡杯咖啡")
const coffee = new Coffee('美式', 10);
coffee.cost();
console.log("\n用咖啡机泡杯咖啡")
const maker = new Maker(coffee, 1, 1);
maker.cost();
console.log("\n=========== 装饰器模式结束 ===========");
})()