具体代码
//DBOperator.java
package org.example.test022;
public abstract class DBOperator {
public abstract void connDB();
public void openDB() {
System.out.println("打开数据库");
}
public void useDB() {
System.out.println("使用数据库");
}
public void closeDB() {
System.out.println("关闭数据库");
}
public void process() {
this.connDB();
this.openDB();
this.useDB();
this.closeDB();
}
}
//SQLServerDBOperator.java
package org.example.test022;
public class SQLServerDBOperator extends DBOperator {
@Override
public void connDB() {
System.out.println("连接SqlServer数据库");
}
}
//OracleDBOperator.java
package org.example.test022;
public class OracleDBOperator extends DBOperator {
@Override
public void connDB() {
System.out.println("连接Oracle数据库");
}
}
//Main.java
package org.example.test022;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请选择你想要连接的数据库:1、SqlServer数据库;2、Oracle数据库");
int i = sc.nextInt();
DBOperator connectionTemplateMethod;
if (i == 1) {
connectionTemplateMethod = new SQLServerDBOperator();
connectionTemplateMethod.process();
}
else if (i == 2) {
connectionTemplateMethod = new OracleDBOperator();
connectionTemplateMethod.process();
}
else {
System.out.println("没有提供这种数据库类型呦~");
}
}
}
运行结果