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 デザイン パターンのビデオ チュートリアルからのものです。
factory.createConnection() は抽象化ではなく具体的な実装を返すため、TestConnection クラスは具体的な実装に依存するためです。
代わりにこれを行うことでこれを修正できますか?
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;
}