2016-09-18 73 views
0

我是新来的Java接口,即使我理解这个概念,各地纷纷看到了很多例子,知道它优于继承在某些情况下,因为它给你更多的灵活性和较小的依赖性。接口的概念

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

所以我一直在试图建立这个接口的地图。目前,我一直在使用Mapbox平台而不是Google Maps。我认为在未来我想要使用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(); 
} 

所以,我认为这并不重要我想利用这个平台,我可以利用这个接口就知道我必须在地图实现哪些方法类。

但是,它感觉像缺少某些东西,其设计或目的不正确。 这是使用接口的正确方法吗?

回答

1

这是使用接口的正确方法是什么?

是的!如果你像这样使用接口,接口肯定可以提供更多的灵活性。

感觉就像缺少某些东西,其设计或目的不正确。

也许你应该创建一个名为IMarker的界面和接口称为ICamera而是采用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(); 
} 
+0

这是工作,谢谢 – AndroidDev