Template approach: Define an execution template (skeleton) and parameterize some dynamic processes and values so that different results can be produced based on different parameters.

For example: the JDK AQS (AbstractQueueSynchronizer) is to use the template method pattern. AQS has defined the process and details of thread synchronization, but only five methods are not implemented, and subclasses are responsible for specific implementation. These five methods are as follows:

These five methods constrain how threads should acquire and release “resources.” When multithreading is running, it is inevitable to run out of resources. In this case, the four methods of AQS (starting with try) are used to obtain resources in exclusive or shared mode. Since AQS is not responsible for implementing these four methods, I’ll use CountDownLatch, a subclass of AQS, as an example:

CountDownLatch inherits AQS and implements the tryAcquireShared and tryRealseShared methods, which define how resources should be obtained. In the end, AQS will use CountDownLatch’s two methods to determine the subsequent execution process. AQS doAcquireShared:

Model analysis:

1, the separation of invariance and change, and the invariance of the template, the change of the parameterization, form a template, greatly improve the template utilization rate at the same time, but also can combine the specific parameters to produce different results.