gpt4 book ai didi

java - 不理解 java 教程中提到的如何将接口(interface)用作 API 的主题。不要得到顿悟时刻

转载 作者:行者123 更新时间:2023-12-01 08:08:26 25 4
gpt4 key购买 nike

当我试图理解 java 中的接口(interface)时,我很难获得“啊哈”的时刻。根据 java 教程网站,在接口(interface)部分他们说:

Typically, a company sells a software package that contains complex methods that another company wants to use in its own software product. An example would be a package of digital image processing methods that are sold to companies making end-user graphics programs. The image processing company writes its classes to implement an interface, which it makes public to its customers. The graphics company then invokes the image processing methods using the signatures and return types defined in the interface. While the image processing company's API is made public (to its customers), its implementation of the API is kept as a closely guarded secret—in fact, it may revise the implementation at a later date as long as it continues to implement the original interface that its customers have relied on.

我的问题与上面的解释有关。当他们说: Typically, a company sells a software package that contains complex methods that another company wants to use in its own software product

我很困惑。假设我已经定义了接口(interface),并且我有实现该接口(interface)的实现类。我的客户将如何使用我正在创建的 API?他们无法访问我的实现类,因为根据上面的描述,implementation of the API is kept as a closely guarded secret 。那么这是否意味着我向客户提供的只是一个用许多方法定义的接口(interface)。而实际的实现需要客户来完成吗?请阐明整个概念和界面的使用。我不太明白。感谢并抱歉提出菜鸟问题

最佳答案

也许一个例子可以提供帮助。

假设您有以下类/接口(interface):

public interface ImageApi {
Image create(int width, int height, Color c);
}

class ImageApiImpl implements ImageApi {
@Override
public Image create(int width, int height, Color c) {
... // implementation
}
}

public ImageApiFactory {
public static ImageApi getImageApi() {
return new ImageApiImpl();
}
}

客户端可以通过以下方式使用此 Api:

ImageApi api = ImageApiFactory.getImageApi();
Image image = api.create(128, 128, Color.Blue);

现在我们假设开发此 API 的公司找到了一种更快的创建图像的方法。不幸的是,新方法仅适用于 Windows 系统。他们将能够执行以下操作:

class FastImageApiImpl implements ImageApi {
@Override
public Image create(int width, int height, Color c) {
... // faster windows specfic implementation
}
}

public ImageApiFactory {
public static ImageApi getImageApi() {
if (isWindowsSystem()) {
return new FastImageApiImpl();
}
return new ImageApiImpl();
}
}

客户端代码保持不变,因为两个 API 实现共享相同的接口(interface)。客户端不知 Prop 体的实现。

关于java - 不理解 java 教程中提到的如何将接口(interface)用作 API 的主题。不要得到顿悟时刻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19478935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com