0
点赞
收藏
分享

微信扫一扫

状态-策略-职责链

笑望叔叔 2022-03-12 阅读 25

一、状态模式

二、策略模式

1. JDBC案列查询

接口

  • 接口负责数据的转换,具体怎么转换,需要开发者自己实现;
package com.day.dreamer.thread.day01;

import java.sql.ResultSet;

/**
 * @author EShu
 */
public interface IHandleResult<T> {

    /**
     * 1. 使用范形,保证返回的值为任意类型
     *    具体是什么样子,自己去手动实现
     */
    T handle(ResultSet resultSet);
}

查询数据类

  • 调用该类时候,只需要自己实现对应的处理结果的类,就可以实现对不同数据库的查询的结果的处理;
  • 每个类功能单一,职责分明;
package com.day.dreamer.thread.day01;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author EShu
 */
public class GetResult {

    private Connection connection;

    public GetResult(Connection connection) {
        this.connection = connection;
    }

    public <T> T getResult(IHandleResult<T> iHandleResult, String sql) throws SQLException {
        // 1. 只负责查询结果
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        T handle = iHandleResult.handle(resultSet);
        return handle;
    }
}

2. Runnable接口和Thread 类

Runnable接口

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

Thread 类

public class Thread implements Runnable {

    /* What will be run. */
    private Runnable target;
    
    public Thread(Runnable target) {
        this(null, target, "Thread-" + nextThreadNum(), 0);
    }

    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
}

三、职责链模式

举报

相关推荐

0 条评论