Java一分钟之-设计模式:装饰器模式与代理模式

装饰器模式和代理模式都是在不改变原有对象的基础上,为对象添加新功能的设计模式。在这篇博客中,我们将讨论这两种模式的基本概念、常见问题及如何避免它们,并提供代码示例。
在这里插入图片描述

1. 装饰器模式 (Decorator Pattern)

定义

装饰器模式动态地将责任附加到对象上。若要扩展功能,装饰器提供了比继承更有弹性的替代方案。

常见问题与易错点

  • 过度使用:过度使用装饰器可能导致类的数量过多,增加系统复杂性。
  • 职责模糊:装饰器和被装饰对象之间的职责边界不清晰,可能导致设计混乱。

代码示例

interface Coffee {
    double getCost();
    String getDescription();
}

class SimpleCoffee implements Coffee {
    @Override
    public double getCost() {
        return 5.0;
    }

    @Override
    public String getDescription() {
        return "Simple Coffee";
    }
}

abstract class CoffeeDecorator implements Coffee {
    protected Coffee coffee;

    public CoffeeDecorator(Coffee coffee) {
        this.coffee = coffee;
    }

    @Override
    public double getCost() {
        return coffee.getCost();
    }

    @Override
    public String getDescription() {
        return coffee.getDescription();
    }
}

class MilkCoffee extends CoffeeDecorator {
    public MilkCoffee(Coffee coffee) {
        super(coffee);
    }

    @Override
    public double getCost() {
        return super.getCost() + 0.5;
    }

    @Override
    public String getDescription() {
        return super.getDescription() + ", with milk";
    }
}

public class Main {
    public static void main(String[] args) {
        Coffee simpleCoffee = new SimpleCoffee();
        System.out.println(simpleCoffee.getCost());
        System.out.println(simpleCoffee.getDescription());

        Coffee milkCoffee = new MilkCoffee(simpleCoffee);
        System.out.println(milkCoffee.getCost());
        System.out.println(milkCoffee.getDescription());
    }
}

2. 代理模式 (Proxy Pattern)

定义

代理模式为一个对象提供一个代理以控制对该对象的访问。代理对象在客户端和目标对象之间起到中介作用。

常见问题与易错点

  • 额外开销:代理可能会引入额外的性能开销。
  • 过度代理:如果只是为了简单控制访问,可能不需要使用代理。

代码示例

interface Image {
    void display();
}

class RealImage implements Image {
    @Override
    public void display() {
        System.out.println("Displaying real image from disk.");
    }
}

class ProxyImage implements Image {
    private RealImage realImage;
    private boolean isLoaded = false;

    public ProxyImage() {
        // Lazy loading
    }

    @Override
    public void display() {
        if (!isLoaded) {
            realImage = new RealImage();
            isLoaded = true;
        }
        realImage.display();
    }
}

public class Main {
    public static void main(String[] args) {
        Image proxyImage = new ProxyImage();
        proxyImage.display();
    }
}

在实际应用中,装饰器模式用于扩展功能,而代理模式用于控制访问或提供额外功能。理解这两种模式的适用场景,避免上述问题,可以提高代码的可扩展性和可维护性。

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jimaks

您的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值