java创建一个Database接口,包含connect()方法和disconnect()方法,用于连接和断开数据库连接。然后创建一个MySQLDatabase类和一个OracleDatabase类,它们都实现了Database接口,并分别实现了连接和断开连接的方法。
时间: 2024-03-21 08:39:52 浏览: 134
好的,以下是Java语言的实现代码:
```java
public interface Database {
void connect();
void disconnect();
}
public class MySQLDatabase implements Database {
private String host;
private String username;
private String password;
private String database;
public MySQLDatabase(String host, String username, String password, String database) {
this.host = host;
this.username = username;
this.password = password;
this.database = database;
}
@Override
public void connect() {
System.out.println(String.format("Connecting to MySQL database %s at %s as %s...", database, host, username));
// 连接MySQL数据库的代码
System.out.println("Connected to MySQL database.");
}
@Override
public void disconnect() {
System.out.println(String.format("Disconnecting from MySQL database %s at %s...", database, host));
// 断开MySQL数据库连接的代码
System.out.println("Disconnected from MySQL database.");
}
}
public class OracleDatabase implements Database {
private String host;
private String username;
private String password;
private String database;
public OracleDatabase(String host, String username, String password, String database) {
this.host = host;
this.username = username;
this.password = password;
this.database = database;
}
@Override
public void connect() {
System.out.println(String.format("Connecting to Oracle database %s at %s as %s...", database, host, username));
// 连接Oracle数据库的代码
System.out.println("Connected to Oracle database.");
}
@Override
public void disconnect() {
System.out.println(String.format("Disconnecting from Oracle database %s at %s...", database, host));
// 断开Oracle数据库连接的代码
System.out.println("Disconnected from Oracle database.");
}
}
```
以上是一个基本的实现,你可以根据自己的需求对其进行扩展和修改。
阅读全文