Another implementation of Java template method

  Interviewing Litchi FM cups, I found an interesting template usage on the way to AQS, and wrote it down.

  The template method is a very important design pattern, and its shadow can be seen in the data access layer and many plug-in interfaces. The general implementation is to define abstract methods in templates and use their methods to perform algorithms, and let specific templates define customized functions. similar:

public  abstract  class Template {
     public  abstract A productA();
    private  void strategy(){
     // ...... 
    A a = productA();
    // ...... 
    }
}

 

  However, sometimes you may not be able to call productA() an abstract method, analogy you need to use this method in the constructor pattern, that is, in the static inner class pattern;

  However, sometimes your template may have multiple abstract methods, but subclasses are not required to implement all abstract methods, but only need to implement individual ones (refer to acquire() and acquireShare() of AQS synchronizer, you do not need to implement all of them)

  How to implement the template method at this time?

  Here's a good way to use exceptions and code

public class Template {
    public A productA(){
         throw new UnsupportedOperationException();    
    }
    public B productB(){
        throw new UnsupportedOperationException();    
    }

    private void strategy(){
    //......
    A a = productA();
    //......
    }
}

  In this way, if the subclass calls the relevant method, a check exception will be thrown. If the responsibility of a subclass needs to use productA, then the compiler will require that the production method of A must be rewritten or exception handling. Is it perfect?

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325022239&siteId=291194637
Recommended