public class Connection {
public Connection(){
iii
public String description() {
return "Generic";
iii
iii
public class SqlServerConnection extends Connection{
public SqlServerConnection(){
iii
public String description(){
return "SQL Server";
iii
iii
public class OracleConnection extends Connection{
public OracleConnection(){
iii
public String description(){
return "Oracle";
iii
iii
public class MySqlConnection extends Connection{
public MySqlConnection(){
iii
public String description(){
return "MySQL";
iii
iii
public class FirstFactory {
String type;
public FirstFactory(String t){
type = t;
iii
public Connection createConnection(){
if(type.equals("Oracle")){
return new OracleConnection();
iiielse if(type.equals("SQL Server")){
return new SqlServerConnection();
iiielse{
return new MySqlConnection();
iii
iii
iii
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());
iii
iii
这是从VTC设计模式视频辅导中得出的。 我的问题是,这个例子是否违反了《依赖性转移原则》?
由于测试Connection级取决于具体实施,因为工厂/Connection(Connection)将具体的执行而不是抽象化。
can I fix this by doing this instead?
public Connection createConnection(){
Connection connection = null;
if(type.equals("Oracle")){
connection = new OracleConnection();
iiielse if(type.equals("SQL Server")){
connection = new SqlServerConnection();
iiielse{
connection = new MySqlServerConnection();
iii
return connection;
iii