090*_*9EM 11
接口允许您在运行时提供不同的实现,注入依赖关系,单独关注,使用不同的实现进行测试.
只需将接口视为类保证实现的合同即可.实现接口的具体类是无关紧要的.不知道这是否有帮助.
想一些代码可能有所帮助.这并没有解释接口上有更多的东西,继续阅读,但我希望这能让你开始.这里要点是你可以改变实施......
package stack.overflow.example;
public interface IExampleService {
void callExpensiveService();
}
public class TestService implements IExampleService {
@Override
public void callExpensiveService() {
// This is a mock service, we run this as many
// times as we like for free to test our software
}
}
public class ExpensiveService implements IExampleService {
@Override
public void callExpensiveService() {
// This performs some really expensive service,
// Ideally this will only happen in the field
// We'd rather test as much of our software for
// free if possible.
}
}
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// In a test program I might write
IExampleService testService = new TestService();
testService.callExpensiveService();
// Alternatively, in a real program I might write
IExampleService testService = new ExpensiveService();
testService.callExpensiveService();
// The difference above, is that we can vary the concrete
// class which is instantiated. In reality we can use a
// service locator, or use dependency injection to determine
// at runtime which class to implement.
// So in the above example my testing can be done for free, but
// real world users would still be charged. Point is that the interface
// provides a contract that we know will always be fulfilled, regardless
// of the implementation.
}
}
Run Code Online (Sandbox Code Playgroud)
接口可用于许多事情.大多数公共使用的是多态和依赖注入,您可以在运行时更改依赖项.例如,假设您有一个名为Database的接口,它有一个名为的方法getField(...).
public interface Database
{
public void getField(String field);
}
Run Code Online (Sandbox Code Playgroud)
现在假设您在应用程序中使用了两个数据库,具体取决于您的客户端:MySQL和PostgreSQL.你将有两个具体的课程:
public class MySQL implements Database
{
// mysql connection specific code
@Override
public void getField(String field)
{
// retrieve value from MySQL
}
}
Run Code Online (Sandbox Code Playgroud)
和...
public class PostgreSQL implements Database
{
// postgre connection specific code
@Override
public String getField(String field)
{
// retrieve value from Postgre
}
}
Run Code Online (Sandbox Code Playgroud)
现在,根据您的客户端偏好,您可以在main中实例化MySQL或PostgreSQL类
public static void main(String args[])
{
if (args[2].equals("mysql"))
Database db = new MySQL();
else
Database db = new PostgreSQL();
}
//now get the field
String foo = db.getField();
Run Code Online (Sandbox Code Playgroud)
或者您可以使用JS或Ruby的Factory/Abstract Factory或脚本引擎.