c# - 这是门面模式吗?如果不是那又怎样?

标签 c# .net design-patterns

我想弄清楚这个设计模式是什么。当我有需要在单个对象上/为单个对象执行的通用逻辑时,我经常使用它。

我在想也许Facade

例如Validation

公共(public)接口(interface)

public interface IValidator<T>
{
    void Validate(T obj);
}

多个实现

public class CodeValidator<T> : IValidator<T> { public void Validate(T obj) { } }
public class PerfValidator<T> : IValidator<T> { public void Validate(T obj) { } }
public class DotValidator<T> : IValidator<T> { public void Validate(T obj) { } }
public class NetfValidator<T> : IValidator<T> { public void Validate(T obj) { } }

然后一个类采用 IValidatorCollection或直接IEnumerable<IValidator>注入(inject)所有已注册的验证器。

public class PostValidaitonController
{
    private IEnumerable<IValidator<Post>> _validators;

    public PostValidaitonController(IEnumerable<IValidator<Post>> validators)
    {
        _validators = validators;
    }

    public void Validate(Post post)
    {
        foreach (var validator in _validators)
        {
            validator.Validate(post);
        }
    }
}

编辑

我知道这使用 IoC/DI 注入(inject) IValidator<T> 的集合但这不是我要寻找的模式。这是您隐藏 interface 的多个实现的模式后面单interface/class

最佳答案

您给出的示例是策略模式的一个很好的示例。

Validator 策略的实现者和 Validator 的用户都依赖于抽象 IValidator。

这使验证用户不必关心特定验证操作的细节。

这也使验证实现者不必关心给定验证的执行方式或时间。

编辑:事实上,在策略模式的 wiki 条目下,它明确提到了验证:

For instance, a class that performs validation on incoming data may use a strategy pattern to select a validation algorithm based on the type of data, the source of the data, user choice, or other discriminating factors. These factors are not known for each case until run-time, and may require radically different validation to be performed. The validation strategies, encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication.

关于c# - 这是门面模式吗?如果不是那又怎样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28975705/

相关文章:

c# - 如何在Windows应用商店应用程序关闭时保存数据?

c# - 如何使用 CodeDOM/T4/PostSharp/whatever 使用 c# 自动创建(例如)单例?

ios - 从 ViewController 更新 UIView 的 subview

c# - 如何将运行时方法传递给自定义属性或可行的替代方法

c# - 如何从 ResourceDictionary 设置 Button.Command?

c# - XNA 窗口缩放性能

.net - 自托管 WCF 服务的视觉反馈

c# - 为什么在单元测试中实例化ListView时SelectedIndices和SelectedItems不起作用?

c# - 如何使用 LINQ 从 Asp.Net 配置文件属性中查询

java - 福勒的模式 : Dealing with table inheritance in a specific way