Creating and Extending Objects with the Factory Patterns : Factory Pattern « Design Pattern « Java Tutorial






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";
  }
}








34.12.Factory Pattern
34.12.1.A simple static factory method.
34.12.2.Creating and Extending Objects with the Factory Patterns