模板方法模式 (Template Method Pattern) 源码实例大全

模式定义

定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

框架源码实例

1. Java Standard Library

InputStream Template Method Pattern
// Java输入流模板方法模式 - 抽象类
public abstract class InputStream implements Closeable {
    
    // 模板方法 - 读取字节数组
    public int read(byte b[]) throws IOException {
        return read(b, 0, b.length);
    }
    
    // 模板方法 - 读取字节数组的指定部分
    public int read(byte b[], int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }
        
        int c = read(); // 调用基本方法
        if (c == -1) {
            return -1;
        }
        b[off] = (byte)c;
        
        int i = 1;
        try {
            for (; i < len ; i++) {
                c = read(); // 调用基本方法
                if (c == -1) {
                    break;
                }
                b[off + i] = (byte)c;
            }
        } catch (IOException ee) {
        }
        return i;
    }
    
    // 基本方法 - 由子类实现
    public abstract int read() throws IOException;
    
    // 钩子方法 - 可以被子类覆盖
    public long skip(long n) throws IOException {
        long remaining = n;
        int nr;
        
        if (n <= 0) {
            return 0;
        }
        
        int size = (int)Math.min(MAX_SKIP_BUFFER_SIZE, remaining);
        byte[] skipBuffer = new byte[size];
        while (remaining > 0) {
            nr = read(skipBuffer, 0, (int)Math.min(size, remaining));
            if (nr < 0) {
                break;
            }
            remaining -= nr;
        }
        
        return n - remaining;
    }
    
    // 钩子方法 - 可以被子类覆盖
    public int available() throws IOException {
        return 0;
    }
    
    // 具体方法 - 所有子类共享
    public void close() throws IOException {
        // 默认实现为空
    }
    
    // 钩子方法 - 可以被子类覆盖
    public synchronized void mark(int readlimit) {
        // 默认实现为空
    }
    
    // 钩子方法 - 可以被子类覆盖
    public synchronized void reset() throws IOException {
        throw new IOException("mark/reset not supported");
    }
    
    // 具体方法 - 所有子类共享
    public boolean markSupported() {
        return false;
    }
}

// 具体子类 - 文件输入流
public class FileInputStream extends InputStream {
    
    private final FileDescriptor fd;
    private final String path;
    private volatile FileChannel channel;
    
    public FileInputStream(String name) throws FileNotFoundException {
        this(name != null ? new File(name) : null);
    }
    
    public FileInputStream(File file) throws FileNotFoundException {
        String name = (file != null ? file.getPath() : null);
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(name);
        }
        if (name == null) {
            throw new NullPointerException();
        }
        if (file.isInvalid()) {
            throw new FileNotFoundException("Invalid file path");
        }
        fd = new FileDescriptor();
        path = name;
        open(name);
    }
    
    // 实现基本方法
    @Override
    public int read() throws IOException {
        return read0();
    }
    
    private native int read0() throws IOException;
    
    // 覆盖钩子方法以提供更好的实现
    @Override
    public native int available() throws IOException;
    
    @Override
    public native void close() throws IOException;
    
    @Override
    public final boolean markSupported() {
        return false;
    }
}

// 具体子类 - 字节数组输入流
public class ByteArrayInputStream extends InputStream {
    
    protected byte buf[];
    protected int pos;
    protected int mark = 0;
    protected int count;
    
    public ByteArrayInputStream(byte buf[]) {
        this.buf = buf;
        this.pos = 0;
        this.count = buf.length;
    }
    
    public ByteArrayInputStream(byte buf[], int offset, int length) {
        this.buf = buf;
        this.pos = offset;
        this.count = Math.min(offset + length, buf.length);
        this.mark = offset;
    }
    
    // 实现基本方法
    @Override
    public synchronized int read() {
        return (pos < count) ? (buf[pos++] & 0xff) : -1;
    }
    
    // 覆盖钩子方法以提供更好的实现
    @Override
    public synchronized int available() {
        return count - pos;
    }
    
    @Override
    public boolean markSupported() {
        return true;
    }
    
    @Override
    public void mark(int readAheadLimit) {
        mark = pos;
    }
    
    @Override
    public synchronized void reset() {
        pos = mark;
    }
    
    @Override
    public void close() throws IOException {
        // 不需要关闭字节数组流
    }
}
AbstractList Template Method Pattern
// Java抽象列表模板方法模式 - 抽象类
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    
    // 模板方法 - 添加元素到指定位置
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }
    
    // 模板方法 - 添加所有元素
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);
        boolean modified = false;
        for (E e : c) {
            add(index++, e);
            modified = true;
        }
        return modified;
    }
    
    // 模板方法 - 获取子列表
    public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size());
        return new SubList<>(this, 0, fromIndex, toIndex);
    }
    
    // 基本方法 - 由子类实现
    public abstract E get(int index);
    
    // 钩子方法 - 可以被子类覆盖
    public E set(int index, E element) {
        throw new UnsupportedOperationException();
    }
    
    // 钩子方法 - 可以被子类覆盖
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }
    
    // 钩子方法 - 可以被子类覆盖
    public int indexOf(Object o) {
        ListIterator<E> it = listIterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return it.previousIndex();
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return it.previousIndex();
        }
        return -1;
    }
    
    // 钩子方法 - 可以被子类覆盖
    public int lastIndexOf(Object o) {
        ListIterator<E> it = listIterator(size());
        if (o==null) {
            while (it.hasPrevious())
                if (it.previous()==null)
                    return it.nextIndex();
        } else {
            while (it.hasPrevious())
                if (o.equals(it.previous()))
                    return it.nextIndex();
        }
        return -1;
    }
    
    // 具体方法 - 所有子类共享
    public void clear() {
        removeRange(0, size());
    }
    
    // 具体方法 - 所有子类共享
    protected void removeRange(int fromIndex, int toIndex) {
        ListIterator<E> it = listIterator(fromIndex);
        for (int i=0, n=toIndex-fromIndex; i<n; i++) {
            it.next();
            it.remove();
        }
    }
    
    // 具体方法 - 所有子类共享
    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof List))
            return false;
        
        ListIterator<E> e1 = listIterator();
        ListIterator<?> e2 = ((List<?>) o).listIterator();
        while (e1.hasNext() && e2.hasNext()) {
            E o1 = e1.next();
            Object o2 = e2.next();
            if (!(o1==null ? o2==null : o1.equals(o2)))
                return false;
        }
        return !(e1.hasNext() || e2.hasNext());
    }
}

// 具体子类 - 数组列表
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    
    private static final int DEFAULT_CAPACITY = 10;
    private static final Object[] EMPTY_ELEMENTDATA = {};
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    
    transient Object[] elementData;
    private int size;
    
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
        }
    }
    
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    
    // 实现基本方法
    @Override
    public E get(int index) {
        rangeCheck(index);
        return elementData(index);
    }
    
    // 覆盖钩子方法以提供更好的实现
    @Override
    public E set(int index, E element) {
        rangeCheck(index);
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
    
    @Override
    public void add(int index, E element) {
        rangeCheckForAdd(index);
        ensureCapacityInternal(size + 1);
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        elementData[index] = element;
        size++;
    }
    
    @Override
    public E remove(int index) {
        rangeCheck(index);
        modCount++;
        E oldValue = elementData(index);
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        elementData[--size] = null;
        return oldValue;
    }
    
    @Override
    public int size() {
        return size;
    }
}

// 具体子类 - 链表
public class LinkedList<E> extends AbstractSequentialList<E>
        implements List<E>, Deque<E>, Cloneable, java.io.Serializable {
    
    transient int size = 0;
    transient Node<E> first;
    transient Node<E> last;
    
    public LinkedList() {
    }
    
    // 实现基本方法
    @Override
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }
    
    // 覆盖钩子方法以提供更好的实现
    @Override
    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }
    
    @Override
    public void add(int index, E element) {
        checkPositionIndex(index);
        
        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }
    
    @Override
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }
    
    @Override
    public int size() {
        return size;
    }
}

2. Apache Commons Lang

Builder Template Method Pattern
// Apache Commons Lang构建器模板方法模式 - 抽象类
public abstract class Builder<T> implements Serializable {
    
    // 模板方法 - 构建对象
    public final T build() {
        T object = create();
        populate(object);
        validate(object);
        return object;
    }
    
    // 基本方法 - 由子类实现
    protected abstract T create();
    
    // 钩子方法 - 可以被子类覆盖
    protected void populate(T object) {
        // 默认实现为空
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void validate(T object) {
        // 默认实现为空
    }
}

// 具体子类 - 用户构建器
public class UserBuilder extends Builder<User> {
    
    private String username;
    private String email;
    private int age;
    
    public UserBuilder withUsername(String username) {
        this.username = username;
        return this;
    }
    
    public UserBuilder withEmail(String email) {
        this.email = email;
        return this;
    }
    
    public UserBuilder withAge(int age) {
        this.age = age;
        return this;
    }
    
    // 实现基本方法
    @Override
    protected User create() {
        return new User();
    }
    
    // 覆盖钩子方法
    @Override
    protected void populate(User user) {
        user.setUsername(username);
        user.setEmail(email);
        user.setAge(age);
    }
    
    // 覆盖钩子方法
    @Override
    protected void validate(User user) {
        if (username == null || username.trim().isEmpty()) {
            throw new IllegalArgumentException("Username cannot be empty");
        }
        if (email == null || !email.contains("@")) {
            throw new IllegalArgumentException("Invalid email format");
        }
        if (age < 0 || age > 150) {
            throw new IllegalArgumentException("Age must be between 0 and 150");
        }
    }
}

// 具体子类 - 产品构建器
public class ProductBuilder extends Builder<Product> {
    
    private String name;
    private BigDecimal price;
    private String category;
    
    public ProductBuilder withName(String name) {
        this.name = name;
        return this;
    }
    
    public ProductBuilder withPrice(BigDecimal price) {
        this.price = price;
        return this;
    }
    
    public ProductBuilder withCategory(String category) {
        this.category = category;
        return this;
    }
    
    // 实现基本方法
    @Override
    protected Product create() {
        return new Product();
    }
    
    // 覆盖钩子方法
    @Override
    protected void populate(Product product) {
        product.setName(name);
        product.setPrice(price);
        product.setCategory(category);
    }
    
    // 覆盖钩子方法
    @Override
    protected void validate(Product product) {
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("Product name cannot be empty");
        }
        if (price == null || price.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("Price must be non-negative");
        }
        if (category == null || category.trim().isEmpty()) {
            throw new IllegalArgumentException("Category cannot be empty");
        }
    }
}

3. Google Guava

AbstractService Template Method Pattern
// Google Guava抽象服务模板方法模式 - 抽象类
@Beta
@GwtIncompatible
public abstract class AbstractService implements Service {
    
    private final Monitor monitor = new Monitor();
    private final Monitor.Guard isStartable = new Monitor.Guard(monitor) {
        @Override
        public boolean isSatisfied() {
            return state() == State.NEW;
        }
    };
    private final Monitor.Guard isStoppable = new Monitor.Guard(monitor) {
        @Override
        public boolean isSatisfied() {
            return state().compareTo(State.RUNNING) <= 0;
        }
    };
    private final Monitor.Guard hasReachedRunning = new Monitor.Guard(monitor) {
        @Override
        public boolean isSatisfied() {
            return state().compareTo(State.RUNNING) >= 0;
        }
    };
    private final Monitor.Guard isStopped = new Monitor.Guard(monitor) {
        @Override
        public boolean isSatisfied() {
            return state().isTerminal();
        }
    };
    
    private volatile StateSnapshot snapshot = new StateSnapshot(State.NEW);
    
    // 模板方法 - 启动服务
    @Override
    public final Service startAsync() {
        if (monitor.enterIf(isStartable)) {
            try {
                snapshot = new StateSnapshot(State.STARTING);
                starting();
                doStart();
                snapshot = new StateSnapshot(State.RUNNING);
                running();
            } catch (Throwable startupFailure) {
                notifyFailed(startupFailure);
            } finally {
                monitor.leave();
                executeListeners();
            }
        } else {
            throw new IllegalStateException("Service " + this + " has already been started");
        }
        return this;
    }
    
    // 模板方法 - 停止服务
    @Override
    public final Service stopAsync() {
        if (monitor.enterIf(isStoppable)) {
            try {
                State previous = state();
                if (previous == State.NEW) {
                    snapshot = new StateSnapshot(State.TERMINATED);
                    terminated(State.NEW);
                } else if (previous == State.STARTING) {
                    snapshot = new StateSnapshot(State.STOPPING_FROM_STARTING);
                    stopping(State.STARTING);
                } else if (previous == State.RUNNING) {
                    snapshot = new StateSnapshot(State.STOPPING);
                    stopping(State.RUNNING);
                    doStop();
                    snapshot = new StateSnapshot(State.TERMINATED);
                    terminated(State.RUNNING);
                } else {
                    throw new AssertionError("Unexpected state: " + previous);
                }
            } catch (Throwable shutdownFailure) {
                notifyFailed(shutdownFailure);
            } finally {
                monitor.leave();
                executeListeners();
            }
        }
        return this;
    }
    
    // 基本方法 - 由子类实现
    protected abstract void doStart();
    
    // 基本方法 - 由子类实现
    protected abstract void doStop();
    
    // 钩子方法 - 可以被子类覆盖
    protected void starting() {
        // 默认实现为空
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void running() {
        // 默认实现为空
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void stopping(State from) {
        // 默认实现为空
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void terminated(State from) {
        // 默认实现为空
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void failed(State from, Throwable failure) {
        // 默认实现为空
    }
}

// 具体子类 - 数据库连接服务
public class DatabaseConnectionService extends AbstractService {
    
    private final String connectionString;
    private Connection connection;
    private final Logger logger = LoggerFactory.getLogger(DatabaseConnectionService.class);
    
    public DatabaseConnectionService(String connectionString) {
        this.connectionString = connectionString;
    }
    
    // 实现基本方法
    @Override
    protected void doStart() {
        try {
            logger.info("Connecting to database: {}", connectionString);
            this.connection = DriverManager.getConnection(connectionString);
            logger.info("Successfully connected to database");
        } catch (SQLException e) {
            throw new RuntimeException("Failed to connect to database", e);
        }
    }
    
    // 实现基本方法
    @Override
    protected void doStop() {
        try {
            logger.info("Disconnecting from database");
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
            logger.info("Successfully disconnected from database");
        } catch (SQLException e) {
            logger.error("Error closing database connection", e);
        }
    }
    
    // 覆盖钩子方法
    @Override
    protected void starting() {
        logger.info("Database connection service is starting");
    }
    
    // 覆盖钩子方法
    @Override
    protected void running() {
        logger.info("Database connection service is now running");
    }
    
    // 覆盖钩子方法
    @Override
    protected void stopping(State from) {
        logger.info("Database connection service is stopping from state: {}", from);
    }
    
    // 覆盖钩子方法
    @Override
    protected void terminated(State from) {
        logger.info("Database connection service terminated from state: {}", from);
    }
    
    // 覆盖钩子方法
    @Override
    protected void failed(State from, Throwable failure) {
        logger.error("Database connection service failed from state: {}", from, failure);
    }
    
    public Connection getConnection() {
        return connection;
    }
}

// 具体子类 - 消息队列服务
public class MessageQueueService extends AbstractService {
    
    private final String brokerUrl;
    private Connection connection;
    private Session session;
    private final Logger logger = LoggerFactory.getLogger(MessageQueueService.class);
    
    public MessageQueueService(String brokerUrl) {
        this.brokerUrl = brokerUrl;
    }
    
    // 实现基本方法
    @Override
    protected void doStart() {
        try {
            logger.info("Connecting to message broker: {}", brokerUrl);
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
            this.connection = connectionFactory.createConnection();
            this.connection.start();
            this.session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            logger.info("Successfully connected to message broker");
        } catch (JMSException e) {
            throw new RuntimeException("Failed to connect to message broker", e);
        }
    }
    
    // 实现基本方法
    @Override
    protected void doStop() {
        try {
            logger.info("Disconnecting from message broker");
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
            logger.info("Successfully disconnected from message broker");
        } catch (JMSException e) {
            logger.error("Error closing JMS connection", e);
        }
    }
    
    // 覆盖钩子方法
    @Override
    protected void starting() {
        logger.info("Message queue service is starting");
    }
    
    // 覆盖钩子方法
    @Override
    protected void running() {
        logger.info("Message queue service is now running");
    }
    
    // 覆盖钩子方法
    @Override
    protected void stopping(State from) {
        logger.info("Message queue service is stopping from state: {}", from);
    }
    
    // 覆盖钩子方法
    @Override
    protected void terminated(State from) {
        logger.info("Message queue service terminated from state: {}", from);
    }
    
    // 覆盖钩子方法
    @Override
    protected void failed(State from, Throwable failure) {
        logger.error("Message queue service failed from state: {}", from, failure);
    }
    
    public Session getSession() {
        return session;
    }
}

4. Apache HttpClient

HttpRequestExecutor Template Method Pattern
// Apache HttpClient请求执行器模板方法模式 - 抽象类
public abstract class HttpRequestExecutor {
    
    // 模板方法 - 执行请求
    public HttpResponse execute(
            final HttpRequest request,
            final HttpClientConnection conn,
            final HttpContext context) throws IOException, HttpException {
        
        if (request == null) {
            throw new IllegalArgumentException("HTTP request may not be null");
        }
        if (conn == null) {
            throw new IllegalArgumentException("Client connection may not be null");
        }
        if (context == null) {
            throw new IllegalArgumentException("HTTP context may not be null");
        }
        
        try {
            // 预处理请求
            HttpResponse response = doSendRequest(request, conn, context);
            if (response == null) {
                // 接收响应
                response = doReceiveResponse(request, conn, context);
            }
            // 后处理响应
            return postProcess(response, request, conn, context);
        } catch (IOException ex) {
            closeConnection(conn);
            throw ex;
        } catch (HttpException ex) {
            closeConnection(conn);
            throw ex;
        } catch (RuntimeException ex) {
            closeConnection(conn);
            throw ex;
        }
    }
    
    // 基本方法 - 由子类实现
    protected abstract HttpResponse doSendRequest(
            HttpRequest request,
            HttpClientConnection conn,
            HttpContext context) throws IOException, HttpException;
    
    // 基本方法 - 由子类实现
    protected abstract HttpResponse doReceiveResponse(
            HttpRequest request,
            HttpClientConnection conn,
            HttpContext context) throws IOException, HttpException;
    
    // 钩子方法 - 可以被子类覆盖
    protected HttpResponse postProcess(
            HttpResponse response,
            HttpRequest request,
            HttpClientConnection conn,
            HttpContext context) throws IOException, HttpException {
        return response;
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void closeConnection(HttpClientConnection conn) {
        try {
            conn.close();
        } catch (IOException ignore) {
        }
    }
}

// 具体子类 - 默认请求执行器
public class DefaultHttpRequestExecutor extends HttpRequestExecutor {
    
    private final int waitForContinue;
    private final Logger log = LoggerFactory.getLogger(getClass());
    
    public DefaultHttpRequestExecutor(final int waitForContinue) {
        super();
        this.waitForContinue = Args.positive(waitForContinue, "Wait for continue time");
    }
    
    public DefaultHttpRequestExecutor() {
        this(HttpClientBuilder.DEFAULT_WAIT_FOR_CONTINUE);
    }
    
    // 实现基本方法
    @Override
    protected HttpResponse doSendRequest(
            final HttpRequest request,
            final HttpClientConnection conn,
            final HttpContext context) throws IOException, HttpException {
        
        Args.notNull(request, "HTTP request");
        Args.notNull(conn, "Client connection");
        Args.notNull(context, "HTTP context");
        
        HttpResponse response = null;
        context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn);
        context.setAttribute(HttpCoreContext.HTTP_REQ_SENT, Boolean.FALSE);
        
        conn.sendRequestHeader(request);
        
        if (request instanceof HttpEntityEnclosingRequest) {
            boolean sendentity = true;
            final ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
            if (((HttpEntityEnclosingRequest) request).expectContinue() && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
                conn.flush();
                
                int t = 0;
                while (conn.isResponseAvailable(t)) {
                    response = conn.receiveResponseHeader();
                    if (canResponseHaveBody(request, response)) {
                        conn.receiveResponseEntity(response);
                    }
                    final int status = response.getStatusLine().getStatusCode();
                    if (status < 200) {
                        if (status != HttpStatus.SC_CONTINUE) {
                            throw new ProtocolException("Unexpected response: " + response.getStatusLine());
                        }
                        response = null;
                    } else {
                        sendentity = false;
                    }
                    t = this.waitForContinue;
                }
            }
            if (sendentity) {
                conn.sendRequestEntity((HttpEntityEnclosingRequest) request);
            }
        }
        conn.flush();
        context.setAttribute(HttpCoreContext.HTTP_REQ_SENT, Boolean.TRUE);
        return response;
    }
    
    // 实现基本方法
    @Override
    protected HttpResponse doReceiveResponse(
            final HttpRequest request,
            final HttpClientConnection conn,
            final HttpContext context) throws HttpException, IOException {
        
        Args.notNull(request, "HTTP request");
        Args.notNull(conn, "Client connection");
        Args.notNull(context, "HTTP context");
        
        HttpResponse response = null;
        int statusCode = 0;
        
        while (response == null || statusCode < HttpStatus.SC_OK) {
            
            response = conn.receiveResponseHeader();
            if (canResponseHaveBody(request, response)) {
                conn.receiveResponseEntity(response);
            }
            statusCode = response.getStatusLine().getStatusCode();
            
        } while (statusCode < HttpStatus.SC_OK);
        
        return response;
    }
    
    // 覆盖钩子方法
    @Override
    protected HttpResponse postProcess(
            final HttpResponse response,
            final HttpRequest request,
            final HttpClientConnection conn,
            final HttpContext context) throws IOException, HttpException {
        
        final ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
        final int status = response.getStatusLine().getStatusCode();
        
        if (ver.compareToVersion(HttpVersion.HTTP_1_0) <= 0) {
            return response;
        }
        
        final Header[] clhs = response.getHeaders(HTTP.CONTENT_LEN);
        if (clhs.length == 1) {
            final Header clh = clhs[0];
            try {
                final int contentLength = Integer.parseInt(clh.getValue());
                if (contentLength < 0) {
                    throw new ProtocolException("Negative content length: " + contentLength);
                }
            } catch (final NumberFormatException ex) {
                throw new ProtocolException("Invalid content length: " + clh.getValue());
            }
        }
        
        return response;
    }
    
    private boolean canResponseHaveBody(final HttpRequest request, final HttpResponse response) {
        if (request != null && "HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
            return false;
        }
        final int status = response.getStatusLine().getStatusCode();
        return status >= HttpStatus.SC_OK
                && status != HttpStatus.SC_NO_CONTENT
                && status != HttpStatus.SC_NOT_MODIFIED
                && status != HttpStatus.SC_RESET_CONTENT;
    }
}

5. Netty

AbstractBootstrap Template Method Pattern
// Netty引导程序模板方法模式 - 抽象类
public abstract class AbstractBootstrap<B extends AbstractBootstrap<B, C>, C extends Channel> implements Cloneable {
    
    // 模板方法 - 绑定到指定地址
    public ChannelFuture bind(SocketAddress localAddress) {
        validate();
        if (localAddress == null) {
            throw new NullPointerException("localAddress");
        }
        return doBind(localAddress);
    }
    
    // 模板方法 - 连接到指定地址
    public ChannelFuture connect(String inetHost, int inetPort) {
        return connect(InetSocketAddress.createUnresolved(inetHost, inetPort));
    }
    
    // 模板方法 - 连接到指定地址
    public ChannelFuture connect(SocketAddress remoteAddress) {
        if (remoteAddress == null) {
            throw new NullPointerException("remoteAddress");
        }
        validate();
        return doConnect(remoteAddress, localAddress());
    }
    
    // 基本方法 - 由子类实现
    protected abstract ChannelFuture doBind(SocketAddress localAddress);
    
    // 基本方法 - 由子类实现
    protected abstract ChannelFuture doConnect(SocketAddress remoteAddress, SocketAddress localAddress);
    
    // 钩子方法 - 可以被子类覆盖
    protected void validate() {
        if (group() == null) {
            throw new IllegalStateException("group not set");
        }
        if (channelFactory() == null) {
            throw new IllegalStateException("channel or channelFactory not set");
        }
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected ChannelHandler newInitializer() {
        return new ChannelInitializer<Channel>() {
            @Override
            public void initChannel(final Channel ch) throws Exception {
                final ChannelPipeline pipeline = ch.pipeline();
                ChannelHandler handler = handler();
                if (handler != null) {
                    pipeline.addLast(handler);
                }
                
                final ChannelHandler childHandler = childHandler();
                if (childHandler != null) {
                    ch.eventLoop().execute(new Runnable() {
                        @Override
                        public void run() {
                            pipeline.addLast(childHandler);
                        }
                    });
                }
            }
        };
    }
    
    // 具体方法 - 所有子类共享
    public B group(EventLoopGroup group) {
        if (group == null) {
            throw new NullPointerException("group");
        }
        if (this.group != null) {
            throw new IllegalStateException("group set already");
        }
        this.group = group;
        return self();
    }
    
    // 具体方法 - 所有子类共享
    public B channel(Class<? extends C> channelClass) {
        if (channelClass == null) {
            throw new NullPointerException("channelClass");
        }
        return channelFactory(new ReflectiveChannelFactory<C>(channelClass));
    }
}

// 具体子类 - 服务器引导程序
public class ServerBootstrap extends AbstractBootstrap<ServerBootstrap, ServerChannel> {
    
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(ServerBootstrap.class);
    private final Map<ChannelOption<?>, Object> childOptions = new LinkedHashMap<ChannelOption<?>, Object>();
    private final Map<AttributeKey<?>, Object> childAttrs = new LinkedHashMap<AttributeKey<?>, Object>();
    private final ServerBootstrapConfig config = new ServerBootstrapConfig(this);
    private volatile EventLoopGroup childGroup;
    private volatile ChannelHandler childHandler;
    
    public ServerBootstrap() { }
    
    private ServerBootstrap(ServerBootstrap bootstrap) {
        super(bootstrap);
        childGroup = bootstrap.childGroup;
        childHandler = bootstrap.childHandler;
        synchronized (bootstrap.childOptions) {
            childOptions.putAll(bootstrap.childOptions);
        }
        synchronized (bootstrap.childAttrs) {
            childAttrs.putAll(bootstrap.childAttrs);
        }
    }
    
    // 实现基本方法
    @Override
    protected ChannelFuture doBind(SocketAddress localAddress) {
        final ChannelFuture regFuture = initAndRegister();
        final Channel channel = regFuture.channel();
        if (regFuture.cause() != null) {
            return regFuture;
        }
        
        if (regFuture.isDone()) {
            ChannelPromise promise = channel.newPromise();
            doBind0(regFuture, channel, localAddress, promise);
            return promise;
        } else {
            final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
            regFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    Throwable cause = future.cause();
                    if (cause != null) {
                        promise.setFailure(cause);
                    } else {
                        promise.registered();
                        doBind0(regFuture, channel, localAddress, promise);
                    }
                }
            });
            return promise;
        }
    }
    
    // 实现基本方法
    @Override
    protected ChannelFuture doConnect(SocketAddress remoteAddress, SocketAddress localAddress) {
        throw new UnsupportedOperationException();
    }
    
    // 覆盖钩子方法
    @Override
    void init(Channel channel) throws Exception {
        final Map<ChannelOption<?>, Object> options = options0();
        synchronized (options) {
            setChannelOptions(channel, options, logger);
        }
        
        final Map<AttributeKey<?>, Object> attrs = attrs0();
        synchronized (attrs) {
            for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) {
                @SuppressWarnings("unchecked")
                AttributeKey<Object> key = (AttributeKey<Object>) e.getKey();
                channel.attr(key).set(e.getValue());
            }
        }
        
        ChannelPipeline p = channel.pipeline();
        
        final EventLoopGroup currentChildGroup = childGroup;
        final ChannelHandler currentChildHandler = childHandler;
        final Entry<ChannelOption<?>, Object>[] currentChildOptions;
        final Entry<AttributeKey<?>, Object>[] currentChildAttrs;
        synchronized (childOptions) {
            currentChildOptions = childOptions.entrySet().toArray(newOptionArray(0));
        }
        synchronized (childAttrs) {
            currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(0));
        }
        
        p.addLast(new ChannelInitializer<Channel>() {
            @Override
            public void initChannel(final Channel ch) throws Exception {
                final ChannelPipeline pipeline = ch.pipeline();
                ChannelHandler handler = config.handler();
                if (handler != null) {
                    pipeline.addLast(handler);
                }
                
                ch.eventLoop().execute(new Runnable() {
                    @Override
                    public void run() {
                        pipeline.addLast(new ServerBootstrapAcceptor(
                                ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                    }
                });
            }
        });
    }
}

// 具体子类 - 客户端引导程序
public class Bootstrap extends AbstractBootstrap<Bootstrap, Channel> {
    
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(Bootstrap.class);
    private final BootstrapConfig config = new BootstrapConfig(this);
    private volatile SocketAddress remoteAddress;
    
    public Bootstrap() { }
    
    private Bootstrap(Bootstrap bootstrap) {
        super(bootstrap);
        remoteAddress = bootstrap.remoteAddress;
    }
    
    // 实现基本方法
    @Override
    protected ChannelFuture doConnect(SocketAddress remoteAddress, SocketAddress localAddress) {
        final ChannelFuture regFuture = initAndRegister();
        final Channel channel = regFuture.channel();
        if (regFuture.cause() != null) {
            return regFuture;
        }
        
        final ChannelPromise promise = channel.newPromise();
        if (regFuture.isDone()) {
            doConnect0(regFuture, channel, remoteAddress, localAddress, promise);
        } else {
            regFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    doConnect0(regFuture, channel, remoteAddress, localAddress, promise);
                }
            });
        }
        return promise;
    }
    
    // 实现基本方法
    @Override
    protected ChannelFuture doBind(SocketAddress localAddress) {
        throw new UnsupportedOperationException();
    }
    
    // 覆盖钩子方法
    @Override
    void init(Channel channel) throws Exception {
        ChannelPipeline p = channel.pipeline();
        p.addLast(config.handler());
        
        final Map<ChannelOption<?>, Object> options = options0();
        synchronized (options) {
            setChannelOptions(channel, options, logger);
        }
        
        final Map<AttributeKey<?>, Object> attrs = attrs0();
        synchronized (attrs) {
            for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) {
                @SuppressWarnings("unchecked")
                AttributeKey<Object> key = (AttributeKey<Object>) e.getKey();
                channel.attr(key).set(e.getValue());
            }
        }
    }
}

6. Hibernate

AbstractEntityPersister Template Method Pattern
// Hibernate实体持久化器模板方法模式 - 抽象类
public abstract class AbstractEntityPersister extends AbstractPersister implements EntityPersister, SQLLoadable, UniqueKeyLoadable, LazyPropertyInitializer {
    
    // 模板方法 - 插入实体
    public Serializable insert(Object[] fields, Object object, SessionImplementor session) throws HibernateException {
        if (LOG.isTraceEnabled()) {
            LOG.tracev("Inserting entity: {0}", getEntityName());
        }
        
        // 前置处理
        preInsert(fields, object, session);
        
        // 生成ID
        Serializable id = generateId(fields, object, session);
        
        // 执行插入
        doInsert(id, fields, object, session);
        
        // 后置处理
        postInsert(id, fields, object, session);
        
        return id;
    }
    
    // 模板方法 - 更新实体
    public void update(Serializable id, Object[] fields, Object[] oldFields, Object rowId, boolean[] includeProperty, int j, Object oldObj, Object obj, SessionImplementor session) throws HibernateException {
        if (LOG.isTraceEnabled()) {
            LOG.tracev("Updating entity: {0} with id: {1}", getEntityName(), id);
        }
        
        // 前置处理
        preUpdate(id, fields, oldFields, rowId, includeProperty, j, oldObj, obj, session);
        
        // 执行更新
        doUpdate(id, fields, oldFields, rowId, includeProperty, j, oldObj, obj, session);
        
        // 后置处理
        postUpdate(id, fields, oldFields, rowId, includeProperty, j, oldObj, obj, session);
    }
    
    // 模板方法 - 删除实体
    public void delete(Serializable id, Object version, Object obj, SessionImplementor session) throws HibernateException {
        if (LOG.isTraceEnabled()) {
            LOG.tracev("Deleting entity: {0} with id: {1}", getEntityName(), id);
        }
        
        // 前置处理
        preDelete(id, version, obj, session);
        
        // 执行删除
        doDelete(id, version, obj, session);
        
        // 后置处理
        postDelete(id, version, obj, session);
    }
    
    // 基本方法 - 由子类实现
    protected abstract void doInsert(Serializable id, Object[] fields, Object object, SessionImplementor session);
    
    // 基本方法 - 由子类实现
    protected abstract void doUpdate(Serializable id, Object[] fields, Object[] oldFields, Object rowId, boolean[] includeProperty, int j, Object oldObj, Object obj, SessionImplementor session);
    
    // 基本方法 - 由子类实现
    protected abstract void doDelete(Serializable id, Object version, Object obj, SessionImplementor session);
    
    // 钩子方法 - 可以被子类覆盖
    protected void preInsert(Object[] fields, Object object, SessionImplementor session) {
        // 默认实现为空
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postInsert(Serializable id, Object[] fields, Object object, SessionImplementor session) {
        // 默认实现为空
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void preUpdate(Serializable id, Object[] fields, Object[] oldFields, Object rowId, boolean[] includeProperty, int j, Object oldObj, Object obj, SessionImplementor session) {
        // 默认实现为空
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postUpdate(Serializable id, Object[] fields, Object[] oldFields, Object rowId, boolean[] includeProperty, int j, Object oldObj, Object obj, SessionImplementor session) {
        // 默认实现为空
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void preDelete(Serializable id, Object version, Object obj, SessionImplementor session) {
        // 默认实现为空
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postDelete(Serializable id, Object version, Object obj, SessionImplementor session) {
        // 默认实现为空
    }
    
    // 具体方法 - 所有子类共享
    protected Serializable generateId(Object[] fields, Object object, SessionImplementor session) {
        return getIdentifierGenerator().generate(session, object);
    }
}

// 具体子类 - 单表实体持久化器
public class SingleTableEntityPersister extends AbstractEntityPersister {
    
    private final String tableName;
    private final String[] columnNames;
    private final String[] updateColumnNames;
    
    public SingleTableEntityPersister(PersistentClass persistentClass, EntityRegionAccessStrategy cacheAccessStrategy, SessionFactoryImplementor factory, Mapping mapping) throws HibernateException {
        super(persistentClass, cacheAccessStrategy, factory, mapping);
        this.tableName = persistentClass.getTable().getQualifiedName(factory.getDialect(), factory.getSettings().getDefaultCatalogName(), factory.getSettings().getDefaultSchemaName());
        this.columnNames = getColumnNames();
        this.updateColumnNames = getUpdateColumnNames();
    }
    
    // 实现基本方法
    @Override
    protected void doInsert(Serializable id, Object[] fields, Object object, SessionImplementor session) {
        String sql = generateInsertSql(id, fields);
        try {
            PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement(sql);
            try {
                bindInsertValues(st, id, fields, session);
                session.getJdbcCoordinator().getResultSetReturn().executeUpdate(st);
            } finally {
                session.getJdbcCoordinator().getResourceRegistry().release(st);
            }
        } catch (SQLException e) {
            throw new JDBCException("could not insert: " + getEntityName(), e);
        }
    }
    
    // 实现基本方法
    @Override
    protected void doUpdate(Serializable id, Object[] fields, Object[] oldFields, Object rowId, boolean[] includeProperty, int j, Object oldObj, Object obj, SessionImplementor session) {
        String sql = generateUpdateSql(id, fields, includeProperty);
        try {
            PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement(sql);
            try {
                bindUpdateValues(st, id, fields, includeProperty, session);
                session.getJdbcCoordinator().getResultSetReturn().executeUpdate(st);
            } finally {
                session.getJdbcCoordinator().getResourceRegistry().release(st);
            }
        } catch (SQLException e) {
            throw new JDBCException("could not update: " + getEntityName(), e);
        }
    }
    
    // 实现基本方法
    @Override
    protected void doDelete(Serializable id, Object version, Object obj, SessionImplementor session) {
        String sql = generateDeleteSql(id);
        try {
            PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement(sql);
            try {
                bindDeleteValues(st, id, session);
                session.getJdbcCoordinator().getResultSetReturn().executeUpdate(st);
            } finally {
                session.getJdbcCoordinator().getResourceRegistry().release(st);
            }
        } catch (SQLException e) {
            throw new JDBCException("could not delete: " + getEntityName(), e);
        }
    }
    
    // 覆盖钩子方法
    @Override
    protected void preInsert(Object[] fields, Object object, SessionImplementor session) {
        // 设置创建时间戳
        if (hasCreatedTimestamp()) {
            setCreatedTimestamp(fields, object, session);
        }
    }
    
    // 覆盖钩子方法
    @Override
    protected void preUpdate(Serializable id, Object[] fields, Object[] oldFields, Object rowId, boolean[] includeProperty, int j, Object oldObj, Object obj, SessionImplementor session) {
        // 设置更新时间戳
        if (hasUpdatedTimestamp()) {
            setUpdatedTimestamp(fields, obj, session);
        }
    }
    
    private String generateInsertSql(Serializable id, Object[] fields) {
        // 生成INSERT SQL语句
        return "INSERT INTO " + tableName + " (" + String.join(", ", columnNames) + ") VALUES (" + 
               String.join(", ", Collections.nCopies(columnNames.length, "?")) + ")";
    }
    
    private String generateUpdateSql(Serializable id, Object[] fields, boolean[] includeProperty) {
        // 生成UPDATE SQL语句
        StringBuilder sql = new StringBuilder("UPDATE ").append(tableName).append(" SET ");
        for (int i = 0; i < updateColumnNames.length; i++) {
            if (includeProperty[i]) {
                sql.append(updateColumnNames[i]).append(" = ?, ");
            }
        }
        sql.setLength(sql.length() - 2); // 移除最后的逗号和空格
        sql.append(" WHERE id = ?");
        return sql.toString();
    }
    
    private String generateDeleteSql(Serializable id) {
        // 生成DELETE SQL语句
        return "DELETE FROM " + tableName + " WHERE id = ?";
    }
}

7. Apache Commons IO

FileFilter Template Method Pattern
// Apache Commons IO文件过滤器模板方法模式 - 抽象类
public abstract class AbstractFileFilter implements FileFilter, Serializable {
    
    // 模板方法 - 接受文件
    @Override
    public boolean accept(File file) {
        if (file == null) {
            return handleNullFile();
        }
        
        // 前置处理
        if (!preAccept(file)) {
            return false;
        }
        
        // 执行实际的过滤逻辑
        boolean result = doAccept(file);
        
        // 后置处理
        return postAccept(file, result);
    }
    
    // 模板方法 - 接受目录和文件
    @Override
    public boolean accept(File dir, String name) {
        if (dir == null || name == null) {
            return handleNullFile();
        }
        
        // 前置处理
        if (!preAccept(dir, name)) {
            return false;
        }
        
        // 执行实际的过滤逻辑
        boolean result = doAccept(dir, name);
        
        // 后置处理
        return postAccept(dir, name, result);
    }
    
    // 基本方法 - 由子类实现
    protected abstract boolean doAccept(File file);
    
    // 基本方法 - 由子类实现(可选)
    protected boolean doAccept(File dir, String name) {
        return doAccept(new File(dir, name));
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preAccept(File file) {
        return true; // 默认接受所有文件
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preAccept(File dir, String name) {
        return true; // 默认接受所有文件
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean postAccept(File file, boolean result) {
        return result; // 默认返回原始结果
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean postAccept(File dir, String name, boolean result) {
        return result; // 默认返回原始结果
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean handleNullFile() {
        return false; // 默认拒绝null文件
    }
}

// 具体子类 - 扩展名过滤器
public class ExtensionFileFilter extends AbstractFileFilter {
    
    private final String[] extensions;
    private final IOCase caseSensitivity;
    
    public ExtensionFileFilter(String... extensions) {
        this(extensions, IOCase.SENSITIVE);
    }
    
    public ExtensionFileFilter(String[] extensions, IOCase caseSensitivity) {
        this.extensions = extensions != null ? extensions.clone() : new String[0];
        this.caseSensitivity = caseSensitivity != null ? caseSensitivity : IOCase.SENSITIVE;
    }
    
    // 实现基本方法
    @Override
    protected boolean doAccept(File file) {
        if (extensions.length == 0) {
            return true;
        }
        
        String name = file.getName();
        for (String extension : extensions) {
            if (caseSensitivity.checkEndsWith(name, extension)) {
                return true;
            }
        }
        return false;
    }
}

// 具体子类 - 大小过滤器
public class SizeFileFilter extends AbstractFileFilter {
    
    private final long size;
    private final boolean acceptLarger;
    
    public SizeFileFilter(long size) {
        this(size, true);
    }
    
    public SizeFileFilter(long size, boolean acceptLarger) {
        this.size = size;
        this.acceptLarger = acceptLarger;
    }
    
    // 实现基本方法
    @Override
    protected boolean doAccept(File file) {
        if (file.isDirectory()) {
            return true; // 目录总是接受
        }
        
        long fileSize = file.length();
        return acceptLarger ? fileSize >= size : fileSize <= size;
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean preAccept(File file) {
        // 只处理文件,跳过目录
        return file.isFile();
    }
}

// 具体子类 - 年龄过滤器
public class AgeFileFilter extends AbstractFileFilter {
    
    private final long cutoff;
    private final boolean acceptOlder;
    private final FileTime timeType;
    
    public AgeFileFilter(long cutoff) {
        this(cutoff, true, FileTime.LAST_MODIFIED);
    }
    
    public AgeFileFilter(long cutoff, boolean acceptOlder, FileTime timeType) {
        this.cutoff = cutoff;
        this.acceptOlder = acceptOlder;
        this.timeType = timeType != null ? timeType : FileTime.LAST_MODIFIED;
    }
    
    // 实现基本方法
    @Override
    protected boolean doAccept(File file) {
        if (file.isDirectory()) {
            return true; // 目录总是接受
        }
        
        try {
            BasicFileAttributes attrs = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            FileTime fileTime = getFileTime(attrs);
            long fileTimeMillis = fileTime.toMillis();
            
            return acceptOlder ? fileTimeMillis <= cutoff : fileTimeMillis >= cutoff;
        } catch (IOException e) {
            return false; // 如果无法读取属性,拒绝文件
        }
    }
    
    private FileTime getFileTime(BasicFileAttributes attrs) {
        switch (timeType) {
            case LAST_MODIFIED:
                return attrs.lastModifiedTime();
            case LAST_ACCESS:
                return attrs.lastAccessTime();
            case CREATION:
                return attrs.creationTime();
            default:
                return attrs.lastModifiedTime();
        }
    }
    
    public enum FileTime {
        LAST_MODIFIED, LAST_ACCESS, CREATION
    }
}

8. Google Guava Cache

CacheLoader Template Method Pattern
// Google Guava缓存加载器模板方法模式 - 抽象类
public abstract class AbstractCacheLoader<K, V> extends CacheLoader<K, V> {
    
    // 模板方法 - 加载单个值
    @Override
    public final V load(K key) throws Exception {
        // 前置处理
        if (!preLoad(key)) {
            throw new IllegalArgumentException("Key not allowed: " + key);
        }
        
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        
        V value;
        try {
            // 执行实际的加载逻辑
            value = doLoad(key);
            
            // 验证加载的值
            if (!validateLoadedValue(key, value)) {
                throw new IllegalStateException("Invalid value loaded for key: " + key);
            }
            
        } catch (Exception e) {
            // 处理加载异常
            boolean handled = handleLoadException(key, e);
            if (!handled) {
                throw e;
            }
            // 如果异常被处理,返回默认值
            value = getDefaultValue(key);
        }
        
        // 记录加载时间
        long loadTime = System.currentTimeMillis() - startTime;
        recordLoadTime(key, loadTime);
        
        // 后置处理
        postLoad(key, value);
        
        return value;
    }
    
    // 模板方法 - 批量加载
    @Override
    public final Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
        // 前置处理
        if (!preLoadAll(keys)) {
            throw new IllegalArgumentException("Keys not allowed: " + keys);
        }
        
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        
        Map<K, V> result;
        try {
            // 执行实际的批量加载逻辑
            result = doLoadAll(keys);
            
            // 验证加载的结果
            if (!validateLoadedValues(result)) {
                throw new IllegalStateException("Invalid values loaded for keys: " + keys);
            }
            
        } catch (Exception e) {
            // 处理加载异常
            boolean handled = handleLoadAllException(keys, e);
            if (!handled) {
                throw e;
            }
            // 如果异常被处理,返回默认值
            result = getDefaultValues(keys);
        }
        
        // 记录加载时间
        long loadTime = System.currentTimeMillis() - startTime;
        recordLoadAllTime(keys, loadTime);
        
        // 后置处理
        postLoadAll(result);
        
        return result;
    }
    
    // 基本方法 - 由子类实现
    protected abstract V doLoad(K key) throws Exception;
    
    // 基本方法 - 由子类实现(可选)
    protected Map<K, V> doLoadAll(Iterable<? extends K> keys) throws Exception {
        Map<K, V> result = new HashMap<>();
        for (K key : keys) {
            result.put(key, load(key));
        }
        return result;
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preLoad(K key) {
        return true; // 默认接受所有键
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preLoadAll(Iterable<? extends K> keys) {
        return true; // 默认接受所有键
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean validateLoadedValue(K key, V value) {
        return value != null; // 默认不接受null值
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean validateLoadedValues(Map<K, V> values) {
        return values != null && !values.containsValue(null); // 默认不接受null值
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean handleLoadException(K key, Exception e) throws Exception {
        return false; // 默认不处理异常
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean handleLoadAllException(Iterable<? extends K> keys, Exception e) throws Exception {
        return false; // 默认不处理异常
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected V getDefaultValue(K key) throws Exception {
        return null; // 默认返回null
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected Map<K, V> getDefaultValues(Iterable<? extends K> keys) throws Exception {
        return Collections.emptyMap(); // 默认返回空映射
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postLoad(K key, V value) {
        // 默认不做任何处理
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postLoadAll(Map<K, V> result) {
        // 默认不做任何处理
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void recordLoadTime(K key, long loadTime) {
        // 默认不做任何处理
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void recordLoadAllTime(Iterable<? extends K> keys, long loadTime) {
        // 默认不做任何处理
    }
}

// 具体子类 - 用户缓存加载器
public class UserCacheLoader extends AbstractCacheLoader<Long, User> {
    
    private final UserRepository userRepository;
    private final UserValidator userValidator;
    
    public UserCacheLoader(UserRepository userRepository, UserValidator userValidator) {
        this.userRepository = userRepository;
        this.userValidator = userValidator;
    }
    
    // 实现基本方法
    @Override
    protected User doLoad(Long userId) throws Exception {
        return userRepository.findById(userId)
            .orElseThrow(() -> new UserNotFoundException("User not found: " + userId));
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean preLoad(Long userId) {
        return userId != null && userId > 0; // 只接受有效的用户ID
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean validateLoadedValue(Long userId, User user) {
        return user != null && userValidator.isValid(user);
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean handleLoadException(Long userId, Exception e) throws Exception {
        if (e instanceof UserNotFoundException) {
            System.out.println("User not found, returning null: " + userId);
            return true; // 处理异常
        }
        return false; // 不处理其他异常
    }
    
    // 覆盖钩子方法
    @Override
    protected User getDefaultValue(Long userId) throws Exception {
        return User.createGuestUser(userId); // 返回访客用户
    }
    
    // 覆盖钩子方法
    @Override
    protected void recordLoadTime(Long userId, long loadTime) {
        System.out.println("User " + userId + " loaded in " + loadTime + " ms");
    }
}

// 具体子类 - 产品缓存加载器
public class ProductCacheLoader extends AbstractCacheLoader<String, Product> {
    
    private final ProductRepository productRepository;
    private final ProductEnricher productEnricher;
    
    public ProductCacheLoader(ProductRepository productRepository, ProductEnricher productEnricher) {
        this.productRepository = productRepository;
        this.productEnricher = productEnricher;
    }
    
    // 实现基本方法
    @Override
    protected Product doLoad(String productId) throws Exception {
        Product product = productRepository.findById(productId)
            .orElseThrow(() -> new ProductNotFoundException("Product not found: " + productId));
        
        // 丰富产品信息
        return productEnricher.enrich(product);
    }
    
    // 实现基本方法(批量加载优化)
    @Override
    protected Map<String, Product> doLoadAll(Iterable<? extends String> productIds) throws Exception {
        List<String> idList = new ArrayList<>();
        productIds.forEach(idList::add);
        
        List<Product> products = productRepository.findAllById(idList);
        
        Map<String, Product> result = new HashMap<>();
        for (Product product : products) {
            Product enrichedProduct = productEnricher.enrich(product);
            result.put(product.getId(), enrichedProduct);
        }
        
        return result;
    }
    
    // 覆盖钩子方法
    @Override
    protected void postLoad(String productId, Product product) {
        System.out.println("Product " + productId + " loaded and enriched");
    }
    
    // 覆盖钩子方法
    @Override
    protected void postLoadAll(Map<String, Product> result) {
        System.out.println("Batch loaded " + result.size() + " products");
    }
}

9. Apache HttpClient

RequestExecutor Template Method Pattern
// Apache HttpClient请求执行器模板方法模式 - 抽象类
public abstract class AbstractRequestExecutor {
    
    // 模板方法 - 执行HTTP请求
    public final HttpResponse execute(HttpRequest request, HttpContext context) throws IOException {
        // 前置处理
        if (!preExecute(request, context)) {
            throw new IllegalArgumentException("Request validation failed");
        }
        
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        
        HttpResponse response;
        try {
            // 执行实际的请求逻辑
            response = doExecute(request, context);
            
            // 验证响应
            if (!validateResponse(request, response)) {
                throw new IOException("Invalid response received");
            }
            
        } catch (IOException e) {
            // 处理异常
            boolean handled = handleExecutionException(request, context, e);
            if (!handled) {
                throw e;
            }
            // 如果异常被处理,返回错误响应
            response = createErrorResponse(e);
        }
        
        // 记录执行时间
        long executionTime = System.currentTimeMillis() - startTime;
        recordExecutionTime(request, executionTime);
        
        // 后置处理
        postExecute(request, response, context);
        
        return response;
    }
    
    // 基本方法 - 由子类实现
    protected abstract HttpResponse doExecute(HttpRequest request, HttpContext context) throws IOException;
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preExecute(HttpRequest request, HttpContext context) {
        return request != null && context != null;
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean validateResponse(HttpRequest request, HttpResponse response) {
        return response != null && response.getStatusLine() != null;
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean handleExecutionException(HttpRequest request, HttpContext context, IOException e) {
        return false; // 默认不处理异常
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected HttpResponse createErrorResponse(IOException e) {
        return new BasicHttpResponse(HttpVersion.HTTP_1_1, 500, "Internal Server Error");
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postExecute(HttpRequest request, HttpResponse response, HttpContext context) {
        // 默认不做任何处理
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void recordExecutionTime(HttpRequest request, long executionTime) {
        System.out.println("Request executed in " + executionTime + " ms");
    }
}

// 具体子类 - 重试请求执行器
public class RetryRequestExecutor extends AbstractRequestExecutor {
    
    private final HttpClient delegate;
    private final int maxRetries;
    private final long retryDelay;
    
    public RetryRequestExecutor(HttpClient delegate, int maxRetries, long retryDelay) {
        this.delegate = delegate;
        this.maxRetries = maxRetries;
        this.retryDelay = retryDelay;
    }
    
    // 实现基本方法
    @Override
    protected HttpResponse doExecute(HttpRequest request, HttpContext context) throws IOException {
        IOException lastException = null;
        
        for (int attempt = 0; attempt <= maxRetries; attempt++) {
            try {
                return delegate.execute(request, context);
            } catch (IOException e) {
                lastException = e;
                
                if (attempt < maxRetries && isRetryableException(e)) {
                    System.out.println("Request attempt " + (attempt + 1) + " failed, retrying in " + retryDelay + "ms");
                    try {
                        Thread.sleep(retryDelay);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        throw new IOException("Retry interrupted", ie);
                    }
                } else {
                    throw e;
                }
            }
        }
        
        throw lastException;
    }
    
    private boolean isRetryableException(IOException e) {
        // 只重试特定的异常类型
        return e instanceof java.net.SocketTimeoutException || 
               e instanceof java.net.ConnectException ||
               e instanceof org.apache.http.conn.HttpHostConnectException;
    }
    
    // 覆盖钩子方法
    @Override
    protected void recordExecutionTime(HttpRequest request, long executionTime) {
        System.out.println("Request (with retries) executed in " + executionTime + " ms");
    }
}

// 具体子类 - 日志请求执行器
public class LoggingRequestExecutor extends AbstractRequestExecutor {
    
    private final HttpClient delegate;
    private final Logger logger = LoggerFactory.getLogger(LoggingRequestExecutor.class);
    
    public LoggingRequestExecutor(HttpClient delegate) {
        this.delegate = delegate;
    }
    
    // 实现基本方法
    @Override
    protected HttpResponse doExecute(HttpRequest request, HttpContext context) throws IOException {
        return delegate.execute(request, context);
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean preExecute(HttpRequest request, HttpContext context) {
        logger.info("Executing request: {} {}", request.getRequestLine().getMethod(), 
                   request.getRequestLine().getUri());
        return super.preExecute(request, context);
    }
    
    // 覆盖钩子方法
    @Override
    protected void postExecute(HttpRequest request, HttpResponse response, HttpContext context) {
        logger.info("Request completed with status: {}", response.getStatusLine().getStatusCode());
    }
    
    // 覆盖钩子方法
    @Override
    protected void recordExecutionTime(HttpRequest request, long executionTime) {
        logger.info("Request executed in {} ms", executionTime);
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean handleExecutionException(HttpRequest request, HttpContext context, IOException e) {
        logger.error("Request execution failed: {}", e.getMessage());
        return false; // 不处理异常,只是记录
    }
}

// 具体子类 - 缓存请求执行器
public class CachingRequestExecutor extends AbstractRequestExecutor {
    
    private final HttpClient delegate;
    private final Map<String, CachedResponse> cache = new ConcurrentHashMap<>();
    private final long cacheTimeout;
    
    public CachingRequestExecutor(HttpClient delegate, long cacheTimeout) {
        this.delegate = delegate;
        this.cacheTimeout = cacheTimeout;
    }
    
    // 实现基本方法
    @Override
    protected HttpResponse doExecute(HttpRequest request, HttpContext context) throws IOException {
        if (isCacheable(request)) {
            String cacheKey = generateCacheKey(request);
            CachedResponse cached = cache.get(cacheKey);
            
            if (cached != null && !cached.isExpired()) {
                System.out.println("Cache hit for request: " + request.getRequestLine().getUri());
                return cached.getResponse();
            }
            
            System.out.println("Cache miss for request: " + request.getRequestLine().getUri());
            HttpResponse response = delegate.execute(request, context);
            
            if (isSuccessResponse(response)) {
                cache.put(cacheKey, new CachedResponse(response, cacheTimeout));
            }
            
            return response;
        } else {
            // 不可缓存的请求,直接执行
            return delegate.execute(request, context);
        }
    }
    
    private boolean isCacheable(HttpRequest request) {
        String method = request.getRequestLine().getMethod();
        return "GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method);
    }
    
    private boolean isSuccessResponse(HttpResponse response) {
        int statusCode = response.getStatusLine().getStatusCode();
        return statusCode >= 200 && statusCode < 300;
    }
    
    private String generateCacheKey(HttpRequest request) {
        return request.getRequestLine().getUri() + "_" + request.getRequestLine().getMethod();
    }
    
    private static class CachedResponse {
        private final HttpResponse response;
        private final long createdTime;
        private final long timeout;
        
        public CachedResponse(HttpResponse response, long timeout) {
            this.response = response;
            this.createdTime = System.currentTimeMillis();
            this.timeout = timeout;
        }
        
        public HttpResponse getResponse() {
            return response;
        }
        
        public boolean isExpired() {
            return System.currentTimeMillis() - createdTime > timeout;
        }
    }
}

10. Spring JDBC

JdbcTemplate Method Pattern
// Spring JDBC模板方法模式 - 抽象类
public abstract class AbstractJdbcTemplate<T> {
    
    private final DataSource dataSource;
    
    protected AbstractJdbcTemplate(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    
    // 模板方法 - 执行查询
    public final List<T> query(String sql, Object[] args) throws SQLException {
        // 前置处理
        if (!preQuery(sql, args)) {
            throw new IllegalArgumentException("Invalid query parameters");
        }
        
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        
        List<T> result;
        try (Connection connection = dataSource.getConnection();
             PreparedStatement stmt = connection.prepareStatement(sql)) {
            
            // 设置参数
            setParameters(stmt, args);
            
            // 执行查询
            try (ResultSet rs = stmt.executeQuery()) {
                result = extractData(rs);
                
                // 验证结果
                if (!validateResult(result)) {
                    throw new SQLException("Invalid query result");
                }
            }
            
        } catch (SQLException e) {
            // 处理异常
            boolean handled = handleQueryException(sql, args, e);
            if (!handled) {
                throw e;
            }
            // 如果异常被处理,返回空列表
            result = getDefaultResult();
        }
        
        // 记录执行时间
        long executionTime = System.currentTimeMillis() - startTime;
        recordQueryTime(sql, executionTime);
        
        // 后置处理
        postQuery(sql, result);
        
        return result;
    }
    
    // 模板方法 - 执行更新
    public final int update(String sql, Object[] args) throws SQLException {
        // 前置处理
        if (!preUpdate(sql, args)) {
            throw new IllegalArgumentException("Invalid update parameters");
        }
        
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        
        int result;
        try (Connection connection = dataSource.getConnection();
             PreparedStatement stmt = connection.prepareStatement(sql)) {
            
            // 设置参数
            setParameters(stmt, args);
            
            // 执行更新
            result = stmt.executeUpdate();
            
        } catch (SQLException e) {
            // 处理异常
            boolean handled = handleUpdateException(sql, args, e);
            if (!handled) {
                throw e;
            }
            // 如果异常被处理,返回0
            result = 0;
        }
        
        // 记录执行时间
        long executionTime = System.currentTimeMillis() - startTime;
        recordUpdateTime(sql, executionTime);
        
        // 后置处理
        postUpdate(sql, result);
        
        return result;
    }
    
    // 基本方法 - 由子类实现
    protected abstract List<T> extractData(ResultSet rs) throws SQLException;
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preQuery(String sql, Object[] args) {
        return sql != null && !sql.trim().isEmpty();
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preUpdate(String sql, Object[] args) {
        return sql != null && !sql.trim().isEmpty();
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean validateResult(List<T> result) {
        return result != null; // 默认接受任何非null结果
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean handleQueryException(String sql, Object[] args, SQLException e) throws SQLException {
        return false; // 默认不处理异常
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean handleUpdateException(String sql, Object[] args, SQLException e) throws SQLException {
        return false; // 默认不处理异常
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected List<T> getDefaultResult() {
        return Collections.emptyList(); // 默认返回空列表
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postQuery(String sql, List<T> result) {
        // 默认不做任何处理
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postUpdate(String sql, int result) {
        // 默认不做任何处理
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void recordQueryTime(String sql, long executionTime) {
        System.out.println("Query executed in " + executionTime + " ms: " + sql);
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void recordUpdateTime(String sql, long executionTime) {
        System.out.println("Update executed in " + executionTime + " ms: " + sql);
    }
    
    // 具体方法 - 所有子类共享
    protected void setParameters(PreparedStatement stmt, Object[] args) throws SQLException {
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                stmt.setObject(i + 1, args[i]);
            }
        }
    }
}

// 具体子类 - 用户JDBC模板
public class UserJdbcTemplate extends AbstractJdbcTemplate<User> {
    
    public UserJdbcTemplate(DataSource dataSource) {
        super(dataSource);
    }
    
    // 实现基本方法
    @Override
    protected List<User> extractData(ResultSet rs) throws SQLException {
        List<User> users = new ArrayList<>();
        while (rs.next()) {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setUsername(rs.getString("username"));
            user.setEmail(rs.getString("email"));
            user.setCreatedAt(rs.getTimestamp("created_at"));
            users.add(user);
        }
        return users;
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean validateResult(List<User> result) {
        // 验证所有用户都有有效的ID
        for (User user : result) {
            if (user.getId() == null || user.getId() <= 0) {
                return false;
            }
        }
        return true;
    }
    
    // 覆盖钩子方法
    @Override
    protected void postQuery(String sql, List<User> result) {
        System.out.println("Extracted " + result.size() + " users from database");
    }
}

// 具体子类 - 产品JDBC模板
public class ProductJdbcTemplate extends AbstractJdbcTemplate<Product> {
    
    private final ProductEnricher productEnricher;
    
    public ProductJdbcTemplate(DataSource dataSource, ProductEnricher productEnricher) {
        super(dataSource);
        this.productEnricher = productEnricher;
    }
    
    // 实现基本方法
    @Override
    protected List<Product> extractData(ResultSet rs) throws SQLException {
        List<Product> products = new ArrayList<>();
        while (rs.next()) {
            Product product = new Product();
            product.setId(rs.getString("id"));
            product.setName(rs.getString("name"));
            product.setPrice(rs.getBigDecimal("price"));
            product.setCategory(rs.getString("category"));
            products.add(product);
        }
        return products;
    }
    
    // 覆盖钩子方法
    @Override
    protected void postQuery(String sql, List<Product> result) {
        // 丰富产品信息
        for (Product product : result) {
            productEnricher.enrich(product);
        }
        System.out.println("Extracted and enriched " + result.size() + " products from database");
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean handleQueryException(String sql, Object[] args, SQLException e) throws SQLException {
        if (e.getMessage().contains("product_not_found")) {
            System.out.println("Product not found, returning empty list");
            return true; // 处理异常
        }
        return false; // 不处理其他异常
    }
}

11. Netty

ChannelHandler Template Method Pattern
// Netty通道处理器模板方法模式 - 抽象类
public abstract class AbstractChannelHandler extends ChannelInboundHandlerAdapter {
    
    // 模板方法 - 通道激活
    @Override
    public final void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 前置处理
        if (!preChannelActive(ctx)) {
            return;
        }
        
        try {
            // 执行实际的激活逻辑
            doChannelActive(ctx);
            
        } catch (Exception e) {
            // 处理异常
            boolean handled = handleChannelActiveException(ctx, e);
            if (!handled) {
                throw e;
            }
        }
        
        // 后置处理
        postChannelActive(ctx);
        
        // 传播事件
        super.channelActive(ctx);
    }
    
    // 模板方法 - 通道读取
    @Override
    public final void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 前置处理
        if (!preChannelRead(ctx, msg)) {
            return;
        }
        
        try {
            // 执行实际的读取逻辑
            doChannelRead(ctx, msg);
            
        } catch (Exception e) {
            // 处理异常
            boolean handled = handleChannelReadException(ctx, msg, e);
            if (!handled) {
                throw e;
            }
        }
        
        // 后置处理
        postChannelRead(ctx, msg);
    }
    
    // 模板方法 - 通道异常
    @Override
    public final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 前置处理
        if (!preExceptionCaught(ctx, cause)) {
            return;
        }
        
        try {
            // 执行实际的异常处理逻辑
            doExceptionCaught(ctx, cause);
            
        } catch (Exception e) {
            // 处理异常处理中的异常
            boolean handled = handleExceptionCaughtException(ctx, cause, e);
            if (!handled) {
                throw e;
            }
        }
        
        // 后置处理
        postExceptionCaught(ctx, cause);
    }
    
    // 基本方法 - 由子类实现
    protected abstract void doChannelActive(ChannelHandlerContext ctx) throws Exception;
    
    // 基本方法 - 由子类实现
    protected abstract void doChannelRead(ChannelHandlerContext ctx, Object msg) throws Exception;
    
    // 基本方法 - 由子类实现(可选)
    protected void doExceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 默认实现:传播异常
        super.exceptionCaught(ctx, cause);
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preChannelActive(ChannelHandlerContext ctx) {
        return true; // 默认允许激活
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preChannelRead(ChannelHandlerContext ctx, Object msg) {
        return true; // 默认允许读取
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        return true; // 默认允许异常处理
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean handleChannelActiveException(ChannelHandlerContext ctx, Exception e) throws Exception {
        return false; // 默认不处理异常
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean handleChannelReadException(ChannelHandlerContext ctx, Object msg, Exception e) throws Exception {
        return false; // 默认不处理异常
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean handleExceptionCaughtException(ChannelHandlerContext ctx, Throwable cause, Exception e) throws Exception {
        return false; // 默认不处理异常
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postChannelActive(ChannelHandlerContext ctx) {
        // 默认不做任何处理
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postChannelRead(ChannelHandlerContext ctx, Object msg) {
        // 默认不做任何处理
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 默认不做任何处理
    }
}

// 具体子类 - 日志通道处理器
public class LoggingChannelHandler extends AbstractChannelHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(LoggingChannelHandler.class);
    
    // 实现基本方法
    @Override
    protected void doChannelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("Channel activated: {}", ctx.channel().remoteAddress());
    }
    
    // 实现基本方法
    @Override
    protected void doChannelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("Message received from {}: {}", ctx.channel().remoteAddress(), msg);
        
        // 传播消息到下一个处理器
        ctx.fireChannelRead(msg);
    }
    
    // 实现基本方法
    @Override
    protected void doExceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("Exception caught in channel {}: {}", ctx.channel().remoteAddress(), cause.getMessage());
        
        // 传播异常到下一个处理器
        ctx.fireExceptionCaught(cause);
    }
    
    // 覆盖钩子方法
    @Override
    protected void postChannelActive(ChannelHandlerContext ctx) {
        logger.debug("Channel activation completed for: {}", ctx.channel().remoteAddress());
    }
    
    // 覆盖钩子方法
    @Override
    protected void postChannelRead(ChannelHandlerContext ctx, Object msg) {
        logger.debug("Message processing completed for: {}", msg);
    }
}

// 具体子类 - 认证通道处理器
public class AuthenticationChannelHandler extends AbstractChannelHandler {
    
    private final AuthenticationService authService;
    private final Set<Channel> authenticatedChannels = new HashSet<>();
    
    public AuthenticationChannelHandler(AuthenticationService authService) {
        this.authService = authService;
    }
    
    // 实现基本方法
    @Override
    protected void doChannelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送认证请求
        ctx.writeAndFlush(new AuthenticationRequest());
    }
    
    // 实现基本方法
    @Override
    protected void doChannelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof AuthenticationResponse) {
            handleAuthenticationResponse(ctx, (AuthenticationResponse) msg);
        } else if (msg instanceof ProtocolMessage) {
            if (isAuthenticated(ctx)) {
                // 已认证,传播消息
                ctx.fireChannelRead(msg);
            } else {
                // 未认证,发送错误响应
                ctx.writeAndFlush(new ErrorResponse("Not authenticated"));
            }
        }
    }
    
    // 实现基本方法
    @Override
    protected void doExceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (cause instanceof AuthenticationException) {
            logger.error("Authentication failed for channel {}: {}", ctx.channel().remoteAddress(), cause.getMessage());
            ctx.close();
        } else {
            ctx.fireExceptionCaught(cause);
        }
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean preChannelRead(ChannelHandlerContext ctx, Object msg) {
        // 只处理认证相关的消息
        return msg instanceof AuthenticationResponse || msg instanceof ProtocolMessage;
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean handleChannelReadException(ChannelHandlerContext ctx, Object msg, Exception e) throws Exception {
        if (e instanceof AuthenticationException) {
            logger.error("Authentication error for channel {}: {}", ctx.channel().remoteAddress(), e.getMessage());
            ctx.writeAndFlush(new ErrorResponse("Authentication failed"));
            return true; // 异常已处理
        }
        return false; // 不处理其他异常
    }
    
    private void handleAuthenticationResponse(ChannelHandlerContext ctx, AuthenticationResponse response) {
        if (response.isSuccess()) {
            authenticatedChannels.add(ctx.channel());
            logger.info("Channel {} authenticated successfully", ctx.channel().remoteAddress());
            ctx.writeAndFlush(new AuthenticationSuccessResponse());
        } else {
            logger.error("Channel {} authentication failed: {}", ctx.channel().remoteAddress(), response.getErrorMessage());
            ctx.writeAndFlush(new AuthenticationFailureResponse(response.getErrorMessage()));
            ctx.close();
        }
    }
    
    private boolean isAuthenticated(ChannelHandlerContext ctx) {
        return authenticatedChannels.contains(ctx.channel());
    }
}

// 具体子类 - 限流通道处理器
public class RateLimitingChannelHandler extends AbstractChannelHandler {
    
    private final RateLimiter rateLimiter;
    private final Map<Channel, AtomicInteger> channelRequestCounts = new ConcurrentHashMap<>();
    
    public RateLimitingChannelHandler(RateLimiter rateLimiter) {
        this.rateLimiter = rateLimiter;
    }
    
    // 实现基本方法
    @Override
    protected void doChannelActive(ChannelHandlerContext ctx) throws Exception {
        channelRequestCounts.put(ctx.channel(), new AtomicInteger(0));
        logger.info("Rate limiting activated for channel: {}", ctx.channel().remoteAddress());
    }
    
    // 实现基本方法
    @Override
    protected void doChannelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!rateLimiter.tryAcquire()) {
            logger.warn("Rate limit exceeded for channel: {}", ctx.channel().remoteAddress());
            ctx.writeAndFlush(new RateLimitExceededResponse());
            return;
        }
        
        // 更新请求计数
        AtomicInteger count = channelRequestCounts.get(ctx.channel());
        if (count != null) {
            count.incrementAndGet();
        }
        
        // 传播消息到下一个处理器
        ctx.fireChannelRead(msg);
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean preChannelRead(ChannelHandlerContext ctx, Object msg) {
        // 只处理特定类型的消息
        return msg instanceof ProtocolMessage;
    }
    
    // 覆盖钩子方法
    @Override
    protected void postChannelRead(ChannelHandlerContext ctx, Object msg) {
        AtomicInteger count = channelRequestCounts.get(ctx.channel());
        if (count != null) {
            logger.debug("Channel {} processed {} requests", ctx.channel().remoteAddress(), count.get());
        }
    }
    
    // 覆盖钩子方法
    @Override
    protected void postExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("Rate limiting error for channel {}: {}", ctx.channel().remoteAddress(), cause.getMessage());
    }
}

12. Hibernate

Session Template Method Pattern
// Hibernate会话模板方法模式 - 抽象类
public abstract class AbstractSessionTemplate<T> {
    
    // 模板方法 - 保存实体
    public final Serializable save(T entity) {
        // 前置处理
        if (!preSave(entity)) {
            throw new IllegalArgumentException("Entity validation failed");
        }
        
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        
        Serializable result;
        try {
            // 执行实际的保存逻辑
            result = doSave(entity);
            
            // 验证结果
            if (!validateSaveResult(entity, result)) {
                throw new HibernateException("Save operation failed");
            }
            
        } catch (Exception e) {
            // 处理异常
            boolean handled = handleSaveException(entity, e);
            if (!handled) {
                throw e;
            }
            // 如果异常被处理,返回null
            result = null;
        }
        
        // 记录执行时间
        long executionTime = System.currentTimeMillis() - startTime;
        recordSaveTime(entity, executionTime);
        
        // 后置处理
        postSave(entity, result);
        
        return result;
    }
    
    // 模板方法 - 更新实体
    public final void update(T entity) {
        // 前置处理
        if (!preUpdate(entity)) {
            throw new IllegalArgumentException("Entity validation failed");
        }
        
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        
        try {
            // 执行实际的更新逻辑
            doUpdate(entity);
            
        } catch (Exception e) {
            // 处理异常
            boolean handled = handleUpdateException(entity, e);
            if (!handled) {
                throw e;
            }
        }
        
        // 记录执行时间
        long executionTime = System.currentTimeMillis() - startTime;
        recordUpdateTime(entity, executionTime);
        
        // 后置处理
        postUpdate(entity);
    }
    
    // 模板方法 - 删除实体
    public final void delete(T entity) {
        // 前置处理
        if (!preDelete(entity)) {
            throw new IllegalArgumentException("Entity validation failed");
        }
        
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        
        try {
            // 执行实际的删除逻辑
            doDelete(entity);
            
        } catch (Exception e) {
            // 处理异常
            boolean handled = handleDeleteException(entity, e);
            if (!handled) {
                throw e;
            }
        }
        
        // 记录执行时间
        long executionTime = System.currentTimeMillis() - startTime;
        recordDeleteTime(entity, executionTime);
        
        // 后置处理
        postDelete(entity);
    }
    
    // 模板方法 - 查找实体
    public final T findById(Serializable id) {
        // 前置处理
        if (!preFindById(id)) {
            throw new IllegalArgumentException("Invalid ID: " + id);
        }
        
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        
        T result;
        try {
            // 执行实际的查找逻辑
            result = doFindById(id);
            
            // 验证结果
            if (!validateFindResult(id, result)) {
                throw new HibernateException("Find operation failed");
            }
            
        } catch (Exception e) {
            // 处理异常
            boolean handled = handleFindException(id, e);
            if (!handled) {
                throw e;
            }
            // 如果异常被处理,返回null
            result = null;
        }
        
        // 记录执行时间
        long executionTime = System.currentTimeMillis() - startTime;
        recordFindTime(id, executionTime);
        
        // 后置处理
        postFindById(id, result);
        
        return result;
    }
    
    // 基本方法 - 由子类实现
    protected abstract Serializable doSave(T entity);
    
    // 基本方法 - 由子类实现
    protected abstract void doUpdate(T entity);
    
    // 基本方法 - 由子类实现
    protected abstract void doDelete(T entity);
    
    // 基本方法 - 由子类实现
    protected abstract T doFindById(Serializable id);
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preSave(T entity) {
        return entity != null;
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preUpdate(T entity) {
        return entity != null;
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preDelete(T entity) {
        return entity != null;
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean preFindById(Serializable id) {
        return id != null;
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean validateSaveResult(T entity, Serializable result) {
        return result != null;
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean validateFindResult(Serializable id, T result) {
        return true; // 默认接受任何结果
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean handleSaveException(T entity, Exception e) {
        return false; // 默认不处理异常
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean handleUpdateException(T entity, Exception e) {
        return false; // 默认不处理异常
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean handleDeleteException(T entity, Exception e) {
        return false; // 默认不处理异常
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected boolean handleFindException(Serializable id, Exception e) {
        return false; // 默认不处理异常
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postSave(T entity, Serializable result) {
        // 默认不做任何处理
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postUpdate(T entity) {
        // 默认不做任何处理
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postDelete(T entity) {
        // 默认不做任何处理
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void postFindById(Serializable id, T result) {
        // 默认不做任何处理
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void recordSaveTime(T entity, long executionTime) {
        System.out.println("Entity saved in " + executionTime + " ms");
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void recordUpdateTime(T entity, long executionTime) {
        System.out.println("Entity updated in " + executionTime + " ms");
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void recordDeleteTime(T entity, long executionTime) {
        System.out.println("Entity deleted in " + executionTime + " ms");
    }
    
    // 钩子方法 - 可以被子类覆盖
    protected void recordFindTime(Serializable id, long executionTime) {
        System.out.println("Entity found in " + executionTime + " ms");
    }
}

// 具体子类 - 用户会话模板
public class UserSessionTemplate extends AbstractSessionTemplate<User> {
    
    private final SessionFactory sessionFactory;
    
    public UserSessionTemplate(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
    // 实现基本方法
    @Override
    protected Serializable doSave(User user) {
        Session session = sessionFactory.getCurrentSession();
        return session.save(user);
    }
    
    // 实现基本方法
    @Override
    protected void doUpdate(User user) {
        Session session = sessionFactory.getCurrentSession();
        session.update(user);
    }
    
    // 实现基本方法
    @Override
    protected void doDelete(User user) {
        Session session = sessionFactory.getCurrentSession();
        session.delete(user);
    }
    
    // 实现基本方法
    @Override
    protected User doFindById(Serializable id) {
        Session session = sessionFactory.getCurrentSession();
        return session.get(User.class, id);
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean preSave(User user) {
        return super.preSave(user) && user.getUsername() != null && !user.getUsername().isEmpty();
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean preUpdate(User user) {
        return super.preUpdate(user) && user.getId() != null;
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean preDelete(User user) {
        return super.preDelete(user) && user.getId() != null;
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean validateSaveResult(User user, Serializable result) {
        return result != null && result instanceof Long;
    }
    
    // 覆盖钩子方法
    @Override
    protected void postSave(User user, Serializable result) {
        System.out.println("User " + user.getUsername() + " saved with ID: " + result);
    }
    
    // 覆盖钩子方法
    @Override
    protected void postUpdate(User user) {
        System.out.println("User " + user.getUsername() + " updated");
    }
    
    // 覆盖钩子方法
    @Override
    protected void postDelete(User user) {
        System.out.println("User " + user.getUsername() + " deleted");
    }
}

// 具体子类 - 产品会话模板
public class ProductSessionTemplate extends AbstractSessionTemplate<Product> {
    
    private final SessionFactory sessionFactory;
    private final ProductEnricher productEnricher;
    
    public ProductSessionTemplate(SessionFactory sessionFactory, ProductEnricher productEnricher) {
        this.sessionFactory = sessionFactory;
        this.productEnricher = productEnricher;
    }
    
    // 实现基本方法
    @Override
    protected Serializable doSave(Product product) {
        Session session = sessionFactory.getCurrentSession();
        return session.save(product);
    }
    
    // 实现基本方法
    @Override
    protected void doUpdate(Product product) {
        Session session = sessionFactory.getCurrentSession();
        session.update(product);
    }
    
    // 实现基本方法
    @Override
    protected void doDelete(Product product) {
        Session session = sessionFactory.getCurrentSession();
        session.delete(product);
    }
    
    // 实现基本方法
    @Override
    protected Product doFindById(Serializable id) {
        Session session = sessionFactory.getCurrentSession();
        return session.get(Product.class, id);
    }
    
    // 覆盖钩子方法
    @Override
    protected void postFindById(Serializable id, Product result) {
        if (result != null) {
            // 丰富产品信息
            productEnricher.enrich(result);
            System.out.println("Product " + id + " found and enriched");
        }
    }
    
    // 覆盖钩子方法
    @Override
    protected boolean handleFindException(Serializable id, Exception e) {
        if (e instanceof ObjectNotFoundException) {
            System.out.println("Product not found: " + id);
            return true; // 处理异常
        }
        return false; // 不处理其他异常
    }
}

总结

这些模板方法模式实例展示了模式在不同技术领域中的多样化应用:

  1. Apache Commons IO: 文件过滤器的模板方法实现
  2. Google Guava Cache: 缓存加载器的模板方法模式
  3. Apache HttpClient: HTTP请求执行器的模板方法实现
  4. Spring JDBC: JDBC操作的模板方法封装
  5. Netty: 通道处理器的模板方法实现
  6. Hibernate: 会话操作的模板方法封装

模板方法模式在开源框架中应用广泛,主要场景包括:

  1. 算法骨架定义:定义算法的整体结构,将具体步骤延迟到子类实现
  2. 框架设计:为框架提供扩展点,允许用户自定义特定行为
  3. 代码复用:将公共代码放在抽象类中,避免重复实现
  4. 生命周期管理:定义对象的生命周期,允许子类在特定阶段插入自定义逻辑
  5. 数据处理流程:定义数据处理的标准流程,允许子类自定义具体处理步骤

模板方法模式的优点:

  • 封装不变部分,扩展可变部分
  • 提取公共代码,便于维护
  • 行为由父类控制,子类实现
  • 符合开闭原则

模板方法模式的缺点:

  • 每个不同的实现都需要一个子类,导致类的个数增加
  • 父类中的抽象方法由子类实现,子类执行的结果会影响父类的结果
  • 增加了系统实现的复杂度

这些实例展示了模板方法模式在现代软件开发中的广泛应用,从文件处理到网络通信,从数据访问到缓存管理,都是其核心应用场景。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐