简体   繁体   中英

Data Acces Objects Factory Design Pattern in React?

I'm currently going through some tutorial about React Design Patterns, subject: Custom Hooks. While the concept feels awesome and seems familiar to me, the solution below provided by the tutor made me question how to deal with different data sources. Is there something like the above mentioned DAO Factory Pattern, you can find in Frameworks like J2E? Or how is the common approach to handle this challenges in React to make the code maintainable?

My first intension woulda be throwing the stuff into a Factory Component and having implementations for the specific providers, basically like it is shown in the two other Code snippets bewlow. Is this the regular wayt to do it?

Any help, tips, additional sources to learn this would be highly appreciated.

Here's the solution, with the both possible implementations thrown into the React Form Component:

import axios from 'axios';
import { useDataSource } from './useDataSource';
import { useResource } from './useResource';
import { useUser } from './useUser';

const serverResource = resourceUrl => async () => {
    const response = await axios.get(resourceUrl);
    return response.data;
};

const localStorageResource = key => () => {
    return localStorage.getItem(key);
}

export const UserInfo = ({ userId }) => {
    // const user = useResource(`/users/${userId}`);
    const user = useDataSource(serverResource(`/users/${userId}`));
    const message = useDataSource(localStorageResource('message'));

    const { name, age, hairColor, hobbies } = user || {};

    return user ? (
        <>
        <h3>{name}</h3>
        <p>Age: {age} years</p>
        <p>Hair Color: {hairColor}</p>
        <h3>Hobbies:</h3>
        <ul>
            {hobbies.map(hobby => <li key={hobby}>{hobby}</li>)}
        </ul>
        </>
    ) : <p>Loading...</p>;
}

And here's the DAO Factory Pattern example provided by Oracle: src: https://www.oracle.com/java/technologies/dataaccessobject.html

// Abstract class DAO Factory
public abstract class DAOFactory {

  // List of DAO types supported by the factory
  public static final int CLOUDSCAPE = 1;
  public static final int ORACLE = 2;
  public static final int SYBASE = 3;
  ...

  // There will be a method for each DAO that can be 
  // created. The concrete factories will have to 
  // implement these methods.
  public abstract CustomerDAO getCustomerDAO();
  public abstract AccountDAO getAccountDAO();
  public abstract OrderDAO getOrderDAO();
  ...

  public static DAOFactory getDAOFactory(
      int whichFactory) {
  
    switch (whichFactory) {
      case CLOUDSCAPE: 
          return new CloudscapeDAOFactory();
      case ORACLE    : 
          return new OracleDAOFactory();      
      case SYBASE    : 
          return new SybaseDAOFactory();
      ...
      default           : 
          return null;
    }
  }
}

...with a concrete implementation:

// Cloudscape concrete DAO Factory implementation
import java.sql.*;

public class CloudscapeDAOFactory extends DAOFactory {
  public static final String DRIVER=
    "COM.cloudscape.core.RmiJdbcDriver";
  public static final String DBURL=
    "jdbc:cloudscape:rmi://localhost:1099/CoreJ2EEDB";

  // method to create Cloudscape connections
  public static Connection createConnection() {
    // Use DRIVER and DBURL to create a connection
    // Recommend connection pool implementation/usage
  }
  public CustomerDAO getCustomerDAO() {
    // CloudscapeCustomerDAO implements CustomerDAO
    return new CloudscapeCustomerDAO();
  }
  public AccountDAO getAccountDAO() {
    // CloudscapeAccountDAO implements AccountDAO
    return new CloudscapeAccountDAO();
  }
  public OrderDAO getOrderDAO() {
    // CloudscapeOrderDAO implements OrderDAO
    return new CloudscapeOrderDAO();
  }
  ...
}

how is the common approach to handle this challenges in React to make the code maintainable?

sure you can. As design patterns do not depend on programming language.

If you are using TypeScript, then you can use Abstract class

If you are using plain JavaScript, then you can use the following approach https://stackoverflow.com/a/48428063/

An example of using Factory in React can be seen here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM