简体   繁体   English

包装对静态方法/变量的访问的模式名称是什么?

[英]What's the pattern name for wrapping access to static methods/variables?

Following on from the question How do the Proxy, Decorator, Adapter, and Bridge Patterns differ? 接下来的问题是代理,装饰器,适配器和桥接模式有何不同? , how would you describe the following pattern which I've needed to implement on several occasions? ,您将如何描述我几次需要实现的以下模式?

The scenario is that I'm referencing a static method or variable from a third-party class, but I want to hide it behind an interface so that I can mock it for testing. 场景是我从第三方类引用了静态方法或变量,但我想将其隐藏在接口后面,以便可以对其进行模拟以进行测试。

For example, in Java the commons-lang library has a SystemUtils class with constants IS_OS_WINDOWS etc. I want to run tests which are independent of the underlying OS and mimic various OSs, so I wrap access to the constant as follows: 例如,在Java中,commons-lang库具有一个SystemUtils类,该类具有常量IS_OS_WINDOWS等。我想运行独立于底层OS并模拟各种OS的测试,因此我将对常量的访问包装如下:

interface ISystemUtils {
    boolean isOsWindows();
}

class SystemUtilsImpl implements ISystemUtils {
    @Override
    public boolean isOsWindows() {
        return SystemUtils.IS_OS_WINDOWS;
    }
}

Is this a Proxy, a generic "wrapper", or something else? 这是代理服务器,是通用的“包装器”,还是其他产品?

This is called a Facade : 这称为立面

A facade is an object that provides a simplified interface to a larger body of code, such as a class library. 外观是为大型代码(例如类库)提供简化接口的对象。 A facade can: 外墙可以:

  • make a software library easier to use, understand and test, since the facade has convenient methods for common tasks; 由于立面具有执行常见任务的便捷方法,因此使软件库更易于使用,理解和测试。
  • make the library more readable, for the same reason 出于相同的原因,使库更具可读性
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system 减少外部代码对库内部工作的依赖,因为大多数代码使用外观,因此在开发系统时具有更大的灵活性
  • wrap a poorly designed collection of APIs with a single well-designed API. 用一个设计良好的API来包装设计欠佳的API集合。

The Facade pattern is a good answer, although I do agree that it normally (in my experience at least) expose a number of different operations/classes. 尽管我确实同意(至少以我的经验)它通常会公开许多不同的操作/类,但是Facade模式是一个很好的答案。 With that said, a number of other patterns can also serve the same purpose - Proxy would likely be my first choice, but Adaptor or Mediator could also be a good fit. 话虽如此,许多其他模式也可以达到相同的目的-代理可能是我的首选,但是Adapter或Mediator也很合适。 Another term for this that you may also come across is a " delegate ". 您可能还会遇到的另一个术语是“ 委托 ”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM