Skip to content

意图

表模块用数据库中的每个表的一个类来组织域逻辑,一个类的单个实例包含将作用于数据的各种过程。

解释

真实世界例子

在处理用户系统时,我们需要对用户表进行一些操作。在这种情况下,我们可以使用表模块模式。我们可以创建一个名为 UserTableModule 的类并初始化该类的一个实例来处理用户表中所有行的业务逻辑。

通俗地说

处理数据库表或视图中所有行的业务逻辑的单个实例。

程序示例

在用户系统的例子中,我们需要处理用户登录和用户注册的域逻辑。我们可以使用表模块模式并创建一个 UserTableModule 类的实例来处理用户表中所有行的业务逻辑。

这是基本的“User”实体。

java
@Setter
@Getter
@ToString
@EqualsAndHashCode
@AllArgsConstructor
public class User {
  private int id;
  private String username;
  private String password;
}

Here is the UserTableModule class.

java
public class UserTableModule {
  private final DataSource dataSource;
  private Connection connection = null;
  private ResultSet resultSet = null;
  private PreparedStatement preparedStatement = null;

  public UserTableModule(final DataSource userDataSource) {
    this.dataSource = userDataSource;
  }
  
  /**
   * Login using username and password.
   *
   * @param username the username of a user
   * @param password the password of a user
   * @return the execution result of the method
   * @throws SQLException if any error
   */
  public int login(final String username, final String password) throws SQLException {
  		// Method implementation.

  }

  /**
   * Register a new user.
   *
   * @param user a user instance
   * @return the execution result of the method
   * @throws SQLException if any error
   */
  public int registerUser(final User user) throws SQLException {
  		// Method implementation.
  }
}

App 类中,我们使用 UserTableModule 的实例来处理用户登录和注册。

java
// Create data source and create the user table.
final var dataSource = createDataSource();
createSchema(dataSource);
userTableModule = new UserTableModule(dataSource);

//Initialize two users.
var user1 = new User(1, "123456", "123456");
var user2 = new User(2, "test", "password");

//Login and register using the instance of userTableModule.
userTableModule.registerUser(user1);
userTableModule.login(user1.getUsername(), user1.getPassword());
userTableModule.login(user2.getUsername(), user2.getPassword());
userTableModule.registerUser(user2);
userTableModule.login(user2.getUsername(), user2.getPassword());

deleteSchema(dataSource);

The program output:

java
12:22:13.095 [main] INFO com.iluwatar.tablemodule.UserTableModule - Register successfully!
12:22:13.117 [main] INFO com.iluwatar.tablemodule.UserTableModule - Login successfully!
12:22:13.128 [main] INFO com.iluwatar.tablemodule.UserTableModule - Fail to login!
12:22:13.136 [main] INFO com.iluwatar.tablemodule.UserTableModule - Register successfully!
12:22:13.144 [main] INFO com.iluwatar.tablemodule.UserTableModule - Login successfully!

类图

适用性

在以下情况下使用表模块模式

  • 域逻辑很简单,且数据采用表格形式。
  • 该应用程序仅使用少数共享的通用面向表格的数据结构。

相关模式

鸣谢