解释
装饰器模式
是一种让你的对象穿上漂亮衣服的模式,它可以在不改变对象本身的情况下,给对象增加一些新的功能。就像你可以给你的手机贴个壳,或者给你的电脑换个键盘一样,装饰器模式可以让你的对象变得更有个性和实用
。
适用场景
当你想要给一个已有的类增加一些额外的职责,但又不想通过继承或修改源码来实现时,你可以使用装饰器模式。比如,你想要给一个普通的咖啡加上牛奶、糖、奶泡等各种调料,你就可以用装饰器模式来实现。
优点
装饰器模式
可以让你动态地扩展一个对象的功能,而不需要创建子类或修改原有类。装饰器模式
可以让你组合多个装饰器来实现不同的效果,而不需要创建复杂的子类。装饰器模式
可以让你保持被装饰对象的接口不变,对客户端透明。
缺点
装饰器模式
会增加程序中的类和对象的数量,可能会导致代码复杂度
和维护成本
增加。装饰器模式
可能会影响被装饰对象的性能
和效率
,因为每次调用方法都需要经过多层装饰器。装饰器模式
可能会使得程序结构难以理解和调试,因为被装饰对象和装饰器之间存在多重依赖关系
。
代码实现
PHP
// 定义商品接口
interface Product {
function getPrice(): float;
}
// 实现商品类
class SimpleProduct implements Product {
private $price;
public function __construct(float $price) {
$this->price = $price;
}
public function getPrice(): float {
return $this->price;
}
}
// 定义装饰器接口
interface ProductDecorator extends Product {
}
// 实现商品打折装饰器类
class DiscountedProduct implements ProductDecorator {
private $product;
private $discount;
public function __construct(Product $product, float $discount) {
$this->product = $product;
$this->discount = $discount;
}
public function getPrice(): float {
return $this->product->getPrice() * (1 - $this->discount);
}
}
// 实例化一个商品对象
$product = new SimpleProduct(100.0);
// 对商品进行打折装饰
$discountedProduct = new DiscountedProduct($product, 0.2);
// 打印打折后的价格
echo "原价:{$product->getPrice()},打折后的价格:{$discountedProduct->getPrice()}";
Go
package main
import "fmt"
// 商品接口
type Product interface {
GetPrice() float64
}
// 普通商品
type SimpleProduct struct {
Price float64
}
func (p *SimpleProduct) GetPrice() float64 {
return p.Price
}
// 打折装饰器
type DiscountDecorator struct {
Product Product
Discount float64
}
func (d *DiscountDecorator) GetPrice() float64 {
return d.Product.GetPrice() * (1 - d.Discount)
}
func main() {
// 创建普通商品
product := &SimpleProduct{Price: 100.0}
// 打九折
discountProduct := &DiscountDecorator{
Product: product,
Discount: 0.1,
}
// 输出商品价格
fmt.Println("原价:", product.GetPrice())
fmt.Println("打折后价格:", discountProduct.GetPrice())
}
Java
// 商品接口
interface Product {
double getPrice();
}
// 普通商品
class SimpleProduct implements Product {
private double price;
public SimpleProduct(double price) {
this.price = price;
}
public double getPrice() {
return this.price;
}
}
// 打折装饰器
class DiscountDecorator implements Product {
private Product product;
private double discount;
public DiscountDecorator(Product product, double discount) {
this.product = product;
this.discount = discount;
}
public double getPrice() {
return this.product.getPrice() * (1 - this.discount);
}
}
public class Main {
public static void main(String[] args) {
// 创建普通商品
Product product = new SimpleProduct(100.0);
// 打九折
Product discountProduct = new DiscountDecorator(product, 0.1);
// 输出商品价格
System.out.println("原价:" + product.getPrice());
System.out.println("打折后价格:" + discountProduct.getPrice());
}
}