java - 从各种未知来源检索特定对象的模式/设计方法

标签 java design-patterns

我正在寻找一种有效的方法,从具有共同父级的可变数量的类中检索特定类的对象。

简单来说 寻找ClassA的对象

B类、C类和D类都有不同名称的方法来获取所述对象。 有时我可能需要访问其中的其他对象才能找到我想要的对象。

我刚刚创建了一个名为的单例类

ObjectRetriever 具有一个名为 getObjectFromSource(Object source) 的方法

该方法目前只是一系列if源instanceof ClassC到 做特定的行为。

我能分享的资源数量有限,但希望有一个现有的模式/设计方法。

最佳答案

  1. 如果您无法控制 A-D 类,我相信您会想要使用 Facade 模式,因为这样您就可以慢慢扩展用于简化对此 API 访问的方法集合。
  2. 如果您确实可以控制类 A-D,则最好重新调整类层次结构,可能是通过添加包含 getA 方法的接口(interface)。

Quote from Wikipedia's Facade Pattern reference: http://en.wikipedia.org/wiki/Facade_pattern

The facade pattern (or façade pattern) is a software design pattern commonly used with object-oriented programming. The name is by analogy to an architectural 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 (as per task needs). The Facade design pattern is often used when a system is very complex or difficult to understand because the system has a large number of interdependent classes or its source code is unavailable. This pattern hides the complexities of the larger system and provides a simpler interface to the client. It typically involves a single wrapper class which contains a set of members required by client. These members access the system on behalf of the facade client and hide the implementation details.

关于java - 从各种未知来源检索特定对象的模式/设计方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28566467/

相关文章:

java - 如何在java中调用Paint组件方法

java - 如何将 "=3"与 java 中的单词边界匹配?

java - Autowire 的 Spring Bean 覆盖问题 'byType'

c++ - EEPROM 烧录器的设计模式

design-patterns - 没有全局/单例的 react 模式

java - 安卓|向服务器发送 “POST” JSON 数据

java - 为什么我创建的自定义异常会导致非静态变量错误?

scala - 如何对 2 个以上的情况确定隐式优先级

C++模式禁止在特定范围外实例化类?

java - JPA 整洁架构