Pattern/Design 从各种未知来源检索特定对象的方法

Pattern/Design approach to retrieve a specific object from various unknown sources

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

简单来说 寻找 ClassA

的对象

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

我只是在制作一个名为class的单身人士

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

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

我只能分享多少资源,但希望有一个现有的 pattern/design 方法。

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

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.

如果您可以修改类 C、B 和 D,您应该创建一个接口,该接口具有检索相关对象的方法。

像这样:

public interface SomeNeatName{ A getA();}


public class B implements SomeNeatName {
    getA(){
        return nameOfVariableHoldingA;
    }
}