假设我想创建一些 CRUD 资源。每个都有 create
、update
、delete
、fetch
和 list
方法。所有这些的返回类型都是相同的,但这些东西的参数会不同。
有没有一种方法可以创建一个定义返回类型和方法名称但允许变量参数的接口(interface)?
例如,
class User implements CRUD {
int create(final String first_name, final String last_name);
}
class Country implements CRUD {
int create(final String name);
}
两者都有一个返回 int
的 create
方法,但每个都有不同的参数。
最佳答案
@Bohemian 解决方案的一个特点是拥有一个通用接口(interface)和封装方法参数的对象
class UserParam {
String fristName;
String lastName;
}
class CountryParam {
String name;
}
interface CRUD<T> {
int create(T param);
}
class User implements CRUD<UserParam> {
int create(UserParam param) {
// do something based on received param of type UserParam
}
}
class Country implements CRUD<CountryParam> {
int create(CountryParam param) {
// do something based on received param of type CountryParam
}
}
关于Java 接口(interface)仅定义方法名称(即变量参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53199254/