Mega Code Archive

 
Categories / Java Tutorial / Design Pattern
 

Creating and Extending Objects with the Factory Patterns

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