| |
34. 12. 2. 建立和扩大对象与工厂模式 |
|
public class MainClass {
public static void main(String args[]) {
SecureFactory factory;
factory = new SecureFactory();
Connection connection = factory.createConnection("Oracle");
System.out.println("You're connecting with " + connection.description());
}
}
class SecureFactory extends ConnectionFactory {
public Connection createConnection(String type) {
if (type.equals("Oracle")) {
return new SecureOracleConnection();
} else if (type.equals("SQL Server")) {
return new SecureSqlServerConnection();
} else {
return new SecureMySqlConnection();
}
}
}
abstract class Connection {
public Connection() {
}
public String description() {
return "Generic";
}
}
abstract class ConnectionFactory {
public ConnectionFactory() {
}
protected abstract Connection createConnection(String type);
}
class SqlServerConnection extends Connection {
public SqlServerConnection() {
}
public String description() {
return "SQL Server";
}
}
class SecureSqlServerConnection extends Connection {
public SecureSqlServerConnection() {
}
public String description() {
return "SQL Server secure";
}
}
class SecureOracleConnection extends Connection {
public SecureOracleConnection() {
}
public String description() {
return "Oracle secure";
}
}
class SecureMySqlConnection extends Connection {
public SecureMySqlConnection() {
}
public String description() {
return "MySQL secure";
}
}
|
|
|