2

Suppose I have an interface API and classes FacebookAPI and FlickrAPI that implements this interface,

public interface API {
    Photo getPhoto(int id);
    Album getAlbum(int id);
}

package api;

import domainObjects.Album;
import domainObjects.Photo;

public class FacebookAPI implements API{

    @Override
    public Photo getPhoto(int id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Album getAlbum(int id) {
        // TODO Auto-generated method stub
        return null;
    }

}


import domainObjects.Album;
import domainObjects.Photo;

public class FlickrAPI implements API{

    @Override
    public Photo getPhoto(int id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Album getAlbum(int id) {
        // TODO Auto-generated method stub
        return null;
    }

}

The issue is that I only know that at minimum both APIs(facebook and flickr) requires the photoId. Now suppose that to get a photo FacebookAPI requires AccessToken in addition to Id while FlickAPI requires APIKey + UserId in addition to photoId.

What Design Pattern can i use to solve this issue?

4

3 回答 3

4

Create a Credentials abstract class to be extended by concrete APi implementation and get that in method contracts.

public Album getAlbum(int id, Credentials c) {

and similarily

public FlickrCredentials extends Credentials {
     String APIKey
     String UserId
}

That is only feasible if the authentication method is similar with changing parameters (like URL parameters). The abstract class should specify the contract of the method actually using the values, something like:

public String buildToken();

that could be implemented for instance as:

@Override
public String buildToken() {
     return "APIKey="+getAPIKey()+"&UserId="+getUserId();
}
于 2013-02-02T06:38:58.873 回答
1

不确定您使用的是哪种语言(目标 c?),但如果在 C# 中完成,那么您会想要使用泛型:

public interface API<TIdentifier> {
    Photo getPhoto(TIdentifier id);
    Album getAlbum(TIdentifier id);
}

然后你的课程看起来像这样:

public class FlickrAPI implements API<FlickrIdentifier>
{
    @Override
    public Photo getPhoto(FlickrIdentifier id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Album getAlbum(FlickrIdentifier id) {
        // TODO Auto-generated method stub
        return null;
    }

}

然后你还需要 FlickrIdentifier 类:

public class FlickrIdentifier
{
    public string ApiKey { get; set; }
    public string UserId { get; set; }
}
于 2013-02-02T06:41:45.020 回答
0

Why cant you do something like this

public class FlickrAPI implements API{

  private String key;
  private UserId id;
  public FlickrAPI(String key, UserId id){
    this.key = key;
    this.id = id;
   //rest of initialzation
  }

}

Similarly for the FacebookAPI class

于 2013-02-02T06:37:45.067 回答