public class Connection {
public Connection(){
}
public String description() {
return "Generic";
}
}
public class SqlServerConnection extends Connection{
public SqlServerConnection(){
}
public String description(){
return "SQL Server";
}
}
public class OracleConnection extends Connection{
public OracleConnection(){
}
public String description(){
return "Oracle";
}
}
public class MySqlConnection extends Connection{
public MySqlConnection(){
}
public String description(){
return "MySQL";
}
}
public class FirstFactory {
String type;
public FirstFactory(String t){
type = t;
}
public Connection createConnection(){
if(type.equals("Oracle")){
return new OracleConnection();
}else if(type.equals("SQL Server")){
return new SqlServerConnection();
}else{
return new MySqlConnection();
}
}
}
public class TestConnection {
public static void main(String[] args) {
FirstFactory factory;
factory = new FirstFactory("Oracle");
Connection connection = factory.createConnection(); //createConnection return concrete implementation not an abstraction
System.out.println("You're connection with " + connection.description());
}
}
这是来自 VTC 设计模式视频教程我的问题是这个例子是否违反了依赖倒置原则?
因为 TestConnection 类依赖于具体实现,因为 factory.createConnection() 返回具体实现而不是抽象。
我可以通过这样做来解决这个问题吗?
public Connection createConnection(){
Connection connection = null;
if(type.equals("Oracle")){
connection = new OracleConnection();
}else if(type.equals("SQL Server")){
connection = new SqlServerConnection();
}else{
connection = new MySqlServerConnection();
}
return connection;
}