某系统为了改进数据库操作的性能,自定义数据库连接对象Connection和语句对象Statement,可针对不同类型的数据库提供不同的连接对象和语句对象,如提供Oracle或SQL Server专用连接类和语句类,而且用户可以通过主函数方式根据实际需要动态更换系统数据库。使用抽象工厂模式设计该系统
package 抽象工厂模式;
public interface Connection {
public void connect();
}
package 抽象工厂模式;
public class OracleConnection implements Connection {
@Override
public void connect() {
System.out.println("连接Oracle数据库");
}
}
package 抽象工厂模式;
public class MySQLConnection implements Connection {
@Override
public void connect() {
System.out.println("连接MySQL数据库");
}
}
package 抽象工厂模式;
public interface Statement {
public void executeStatement();
}
package 抽象工厂模式;
public class OracleStatement implements Statement {
@Override
public void executeStatement() {
System.out.println("执行Oracle数据库语句");
}
}
package 抽象工厂模式;
public class MySQLStatement implements Statement {
@Override
public void executeStatement() {
System.out.println("执行MySQL数据库语句");
}
}
package 抽象工厂模式;
public interface DBFactory {
public Connection createConnection();
public Statement createStatement();
}
package 抽象工厂模式;
public class MySQLFactory implements DBFactory {
@Override
public Connection createConnection() {
return new MySQLConnection();
}
@Override
public Statement createStatement() {
return new MySQLStatement();
}
}
package 抽象工厂模式;
public class OracleFactory implements DBFactory {
@Override
public Connection createConnection() {
return new OracleConnection();
}
@Override
public Statement createStatement() {
return new OracleStatement();
}
}
package 抽象工厂模式;
public class Client {
public static void main(String[] args) {
DBFactory factory;
Connection connection;
Statement statement;
factory=new OracleFactory();
connection=factory.createConnection();
statement=factory.createStatement();
connection.connect();
statement.executeStatement();
factory=new MySQLFactory();
connection=factory.createConnection();
statement=factory.createStatement();
connection.connect();
statement.executeStatement();
}
}
java设计模式练习自留。