Abstract Factory

1. Schema definition

Provides an interface for creating a series of related or interdependent objects without specifying their specific types

Is actually abstracted from a series of related factory methods.

The class diagram

Application scenarios

You can use an abstract factory when your program needs to deal with different families of related products, but you don’t want it to depend on concrete classes of those products

advantages

  • You can be sure that the products you get from the factory are compatible with each other
  • Tight coupling between specific product and client code can be avoided
  • Consistent with the principle of single responsibility
  • In line with the open and close principle

JDK source code application

java.sql.Connection
java.sql.Driver
Copy the code

2. Code implementation

Assume that if you want to develop a set of database connection classes, the part that changes is that different databases may have certain differences in implementation; The invariable part is that no matter what database you have, you will need methods such as Connection and command.

Abstract definition:

interface IConnection {
    void connecte(a);
}
interface ICommand {
    void command(a);
}
interface IDatabaseUtils {
    IConnection getConnection(a);
    ICommand getCommand(a);
}
Copy the code

MySQL implementation

class MysqlConnection implements IConnection {

    @Override
    public void connecte(a) {
        System.out.println("MySQL connected"); }}class MysqlCommand implements ICommand {

    @Override
    public void command(a) {
        System.out.println("MySQL commanded"); }}class MySQLDatabaseUtils implements IDatabaseUtils {

    @Override
    public IConnection getConnection(a) {
        return new MysqlConnection();
    }

    @Override
    public ICommand getCommand(a) {
        return newMysqlCommand(); }}Copy the code

Oracle implementation

class OracleConnection implements IConnection {

    @Override
    public void connecte(a) {
        System.out.println("Oracle connected"); }}class OracleCommand implements ICommand {

    @Override
    public void command(a) {
        System.out.println("Oracle commanded"); }}class OracleDatabaseUtils implements IDatabaseUtils {

    @Override
    public IConnection getConnection(a) {
        return new OracleConnection();
    }

    @Override
    public ICommand getCommand(a) {
        return newOracleCommand(); }}Copy the code

Specific use:

public static void main(String[] args) {
    IDatabaseUtils iDatabaseUtils = new OracleDatabaseUtils();
    IConnection connection = iDatabaseUtils.getConnection();
    connection.connecte();
    ICommand command = iDatabaseUtils.getCommand();
    command.command();
}
Copy the code