java - 接口(interface)的概念应用于基于位置的应用程序

标签 java android interface location

尽管我了解这个概念,看过很多示例,并且知道在某些情况下它比继承更受青睐,但我对 java 接口(interface)还是个新手,因为它为您提供了更大的灵 active 和更少的依赖性。

在实践中,我第一次为 Android 构建基于位置的应用程序。我觉得我应该设计一些界面,以便将来可以简化我的工作,因为我假设我可能会再次构建其他基于位置的应用程序。

所以我一直在尝试为 map 构建这个界面。目前,我一直在使用 Mapbox 平台而不是 Google map 。我认为构建一个接口(interface)是个好主意,以防我将来想使用 Google Maps API。

所以我做了这样的事情:

public interface Mapable {

    // Marker
    Object createMarker(String id, Location location, int icon);
    void addMarker(Object object);
    void removeMarker(String id);
    void moveMarker(String id, Location destination);

    // Camera
    Object createCamera();
    void addCamera(Object object);
    void changeZoom(int zoom);
    void setZoomRange(int min, int max);
    void moveCamera(Location location, int zoom);

    void updateElements();
}

所以,我相信我想使用的平台并不重要,我可以利用这个接口(interface)来知道我必须在 Map 类中实现哪些方法。

但是,感觉好像缺少了一些东西,并且其设计或目的不正确。 这是使用接口(interface)的正确方法吗?

最佳答案

Is this the correct way of using interfaces?

是的!如果你这样使用接口(interface),它肯定可以提供更多的灵 active 。

it feels like something is missing and its design or purpose is not correct.

也许您应该创建一个名为 IMarker 的接口(interface)和一个名为 ICamera 的接口(interface),而不是使用 Object 作为标记和相机?

public interface IMarker {
    String getID();
    Location getLocation();
    @DrawableRes
    int getIcon(); // You can also return a Drawable instead, if you want

    // here you can add setters, but I don't think you need to
}

public interface ICamera {
    int getZoom();
    int getMinZoom();
    int getMaxZoom();
    Location getLocation();

    void setZoom(int value);
    void setZoomRange(int min, int max);
    void move(Location location, int zoom);
}

然后你可以像这样编写你的Mappable界面:

public interface Mapable {

    // Marker
    IMarker createMarker(String id, Location location, int icon);
    void addMarker(IMarker marker);
    void removeMarker(String id);
    void moveMarker(String id, Location destination);

    // Camera
    ICamera createCamera();
    void addCamera(ICamera camera);
    // Uncomment this line below if you want to be able to get all cameras
    // ICamera[] getCameras();
    // Uncomment this line below if you want to be able to get the current camera
    // ICamera getCurrentCamera();

    void updateElements();
}

关于java - 接口(interface)的概念应用于基于位置的应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39558059/

相关文章:

java - 在 JTable 中使用空列作为分隔符

java - 打破 @Query 的 LIMIT

java - 如何使用 HashMap 并在 ArrayAdapter 中使用它来在微调器中显示值

java - 如何在界面中声明列表(并向列表添加内容)

javascript - Typescript 提示界面中不存在私有(private)属性

java - driver.switchTo().alert() 不适用于谷歌浏览器和火狐浏览器

java - 如何将 JLabel 作为字符串使用

android - 在 Eclipse 中运行 APK 文件

android - 在 Android 应用程序中处理 Activity 堆栈

java - 为什么每当我在父类 - Android 中触发一个操作时,我的子类方法总是被调用?