design-patterns - 策略模式 VS 装饰模式

标签 design-patterns decorator strategy-pattern

我刚刚发现了两种模式。

  1. 策略模式

  2. 装饰器

Strategy Pattern :-

Strategy pattern gives several algorithms that can be used to perform particular operation or task.

Decorator Pattern :-

Decorator pattern adds some functionality to component.

事实上我发现策略模式和装饰器模式也可以互换使用。

这是链接:- When and How Strategy pattern can be applied instead of decorator pattern?

策略模式和装饰器模式有什么区别?

什么时候应该使用策略模式,什么时候应该使用装饰器模式?

用相同的例子解释两者之间的区别。

最佳答案

策略模式允许您更改运行时使用的某些内容的实现。

装饰器模式允许您在运行时使用附加功能来增强(或添加)现有功能。

主要区别在于更改增强

在您链接到的问题之一中还指出,使用策略模式,消费者会意识到存在不同的选项,而使用装饰器模式,消费者不会意识到附加功能。

举个例子,假设您正在编写一些内容来对元素集合进行排序。因此,您编写一个接口(interface)ISortingStrategy,然后您可以实现几种不同的排序策略BubbleSortStrategyQuickSortStrategyRadixSortStrategy,然后您的应用程序根据现有列表的某些标准选择最合适的策略来对列表进行排序。例如,如果列表中的项目少于 10 个,我们将使用 RadixSortStrategy,如果自上次排序以来添加到列表中的项目少于 10 个,我们将使用 BubbleSortStrategy,否则我们将使用QuickSortStrategy

我们正在更改运行时的排序类型(以便根据一些额外信息提高效率。)这就是策略模式。

现在想象一下,有人要求我们提供每个排序算法用于进行实际排序的频率的日志,并将排序限制为管理员用户。我们可以通过创建一个增强 any ISortingStrategy 的装饰器来添加这两项功能。我们可以创建一个装饰器,记录它用于对某些内容进行排序以及装饰排序策略的类型。我们可以添加另一个装饰器,在调用装饰排序策略之前检查当前用户是否是管理员。

在这里,我们使用装饰器向任何排序策略添加新功能,但不会交换核心排序功能(我们使用不同的策略来改变它)

以下是装饰器外观的示例:

public interface ISortingStrategy
{
    void Sort(IList<int> listToSort);
}

public class LoggingDecorator : ISortingStrategy
{
    private ISortingStrategy decorated;
    public LoggingDecorator(ISortingStrategy decorated)
    {
         this.decorated=decorated;
    }

    void Sort(IList<int> listToSort)
    { 
         Log("sorting using the strategy: " + decorated.ToString();
         decorated.Sort(listToSort);
    }
}

public class AuthorisingDecorator : ISortingStrategy
{
    private ISortingStrategy decorated;
    public AuthorisingDecorator(ISortingStrategy decorated)
    {
         this.decorated=decorated;
    }

    void Sort(IList<int> listToSort)
    { 
         if (CurrentUserIsAdministrator())
         {
             decorated.Sort(listToSort);
         }
         else
         {
             throw new UserNotAuthorizedException("Only administrators are allowed to sort");
         }
    }
}

关于design-patterns - 策略模式 VS 装饰模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26422884/

相关文章:

python - 是否有任何设计模式可以实现抽象类的子类方法的装饰?

c++ - 理解策略模式

java - 使用工厂创建策略

android - 使用 Dagger 2 发送数组列表

c# - 为什么.NET 没有像Java 那样内置观察者模式?

python - 具有多个 View 参数的 Django 装饰器

python - 描述方法调用并记录分析结果的装饰器

java - 针对多种模式验证字符串的最佳方法

java - Method对象相当于Command设计模式中的Command对象吗?

java - 在调用调用代理以聚合来自多个端点的数据的方法时,我可以使用什么模式来部分成功?