This is the 26th day of my participation in the August Text Challenge.More challenges in August

Strategy is also the Strategy pattern, which is similar to the Bridge pattern mentioned above, both of which are the modes of implementation and function separation. You can even say that the policy pattern is a subset of the bridge pattern, with the emphasis on providing different implementations for different scenarios. Whether it’s bridging or policy, one key point is delegation. Delegation is a weak association. The delegated interface or abstract class can have different implementations, and the implementation can be switched flexibly within the principal object. Here is the class diagram for the policy pattern:

The policy mode is often used for hot-swapping algorithms, dynamically switching algorithms based on different calculation results. In AI model validation is useful, in the same scene different options also is very useful, when you return to different calculation logic in gold map query in a line, for example, when you click on walking, bicycles, cars and so on the different options, it will return to the corresponding dynamic route planning, the most common example of this is the strategy pattern.

The code for policy mode is very similar to bridge mode and will not be rewritten. Here is a more efficient implementation – enumeration implementation.

public enum  StrategyEnum {
    WALK {
        @Override
        public Route buildRoute(String a, String b) {
            Route r = doingSomething...
            return r;
        }
    },

    CAR {
        @Override
        public Route buildRoute(String a, String b) {
            Route r = doingSomething...
            returnr; }};public abstract Route buildRoute(String src, String dest);

    public static void main(String[] args) {
       
        Route route1 = StrategyEnum.WALK.buildRoute("a"."b");
        System.out.println(route1);

        
        Route route2 = StrategyEnum.CAR.buildRoute("a"."b"); System.out.println(route2); }}Copy the code

This might seem relatively efficient and elegant than hard coding, but at this point in time, it’s just too much of a hassle. Java is evolving and learning from functional languages, so you can now pass through functions. Yes, Supplier, or Function. Like the following:


public class Strategy {
    public Route runStrategy(Supplier<Route> s) {... }}public class Business {
    private Strategy strategy;

    Route route1 = strategy.runStrategy(()->buildRoute("a"."b"))}Copy the code

I feel that the design pattern needs to be updated to accommodate functional concepts.