teasing

Ridicule first! You have to eat the melon first! Please take a step to read a little bit of the article on the minimalist strategy mode, deep into the author’s heart process, think together, learn together, together happy! Stamp –> Minimalist Policy mode 1.0… Ahem, let’s be serious. Programmers, after all! To be dull and rigid, the author wrote the article, also very satisfied, sent to the students, friends, a magical group, and then friendly programmer friends, on the cheerful ridicule, the atmosphere suddenly rose, they mainly pointed out (attack) the following problems:

  1. Hooks are used with processing logicPairToo much trouble to combine (I think they are nitpicking)
  2. useListTo store the policy is ok, but don’t feelThe genericWrite a little bit how (It’s not your handwriting. What are you afraid of?)
  3. Policy initialization and use are very subtle,levelNot clear,redundantComplex (This is the only thing I admit to myself)

search

After listening to the friendly feedback, I was very frustrated and decided to give up.

Don’t worry. By some coincidence, I came across some articles about enumerations, found them wonderful, and had some bold ideas

  1. Enumeration is already loadedInitialize theCan effectively separate usage and initialization
  2. Enumeration combined policy methods canhiddenDetails of policy implementation, encapsulating related logic
  3. The addition and modification of enumerations is very clear, and the names of enumerations canPoint out effectivelyLogic of the current policy

Code a code (the story is pure fiction, if there are similarities, you must copy mine)

Year close, what everybody cares about of course is how to give shuang son wash white, oh not, be trump left office next home go where, not!!!! What I care most is whether migrant workers can go home for the Spring Festival. The author, also a migrant worker, has a brainwave and provides an advanced system for the village to filter migrant workers’ requests for returning home. The specific logic is shown below

1. The village directly blocked the road, and the migrant workers directly returned the same way

The logical abstraction for each blocking process should look like this

public interface ConsumerStrategy<P.C> {

    /** * The hook that exposes the current policy **@returnDetermine the hook */
    Predicate<P> predicate(a);

    /** * Exposes the consumption logic of the current policy **@returnConsumption logic */
    Consumer<C> consumer(a);

    /** * Actual consumption data **@paramP Hook source *@paramC Source of consumption */
    default void handle(P p, C c) {
        if (this.predicate().test(p)) {
            this.consumer().accept(c); }}}Copy the code

The system maintains a set of blocking query logic, which is as follows

/** ** simplified processing * String represents the risk factor from the region * Integer worker */
enum ReturnHomeStrategy implements ConsumerStrategy<String.Integer> {
    /** * High risk */
    HIGH_RISK(from -> "HIGH_RISK".equals(from), i -> {
        throw new RuntimeException("Roll!");
    }),
    /** * risk */
    MIDDLE_RISK(from -> "MIDDLE_RISK".equals(from), i -> {
        throw new RuntimeException("Roll!");
    }),
    /** * low risk */
    LOW_RISK(from -> "LOW_RISK".equals(from), i -> {
        // Todo if you can, please also go
        // ToDO check
        // Todo quarantines at home
    });

    private final Predicate<String> predicate;

    private final Consumer<Integer> consumer;

    ReturnHomeStrategy(Predicate<String> predicate, Consumer<Integer> consumer) {
        this.predicate = predicate;
        this.consumer = consumer;
    }

    @Override
    public Predicate<String> predicate(a) {
        return this.predicate;
    }

    @Override
    public Consumer<Integer> consumer(a) {
        return this.consumer; }}Copy the code

The operating status of the system is as follows

/** * someone goes home **@paramFrom represents the risk coefficient * from the region@paramId worker */
public void returnHome(String from, Integer id) {
    for(ReturnHomeStrategy value : ReturnHomeStrategy.values()) { value.handle(from, id); }}Copy the code

System is running after a period of time, popular, successful to protect the safety of the village, just village head feel that not enough human, not humanistic care, ask the author have good method, the author belly handguns, something a shake, or give them open a proof, found that reflect the love in the village, the village chief at the deep, slightly The head

2. The village blocked the road directly, but provided written proof that system 2.0 was online

After the revision, the logical abstraction for each blocking process should look like this

public interface FunctionStrategy<P.T.R> {

    /** * The hook that exposes the current policy **@returnDetermine the hook */
    Predicate<P> predicate(a);

    /** * Exposes the production logic of the current policy **@returnConsumption logic */
    Function<T, R> function(a);
}
Copy the code

The system maintains the logic of new roadblocks and issues written certificates

/** ** simplified processing * String represents from the regional risk coefficient * Integer worker * String village issued proof */
enum ReturnHomeStrategy implements FunctionStrategy<String.Integer.String> {
    /** * High risk */
    HIGH_RISK(from -> "HIGH_RISK".equals(from), i -> "Roll!"),
    /** * risk */
    MIDDLE_RISK(from -> "MIDDLE_RISK".equals(from), i -> "Roll!"),
    /** * low risk */
    LOW_RISK(from -> "LOW_RISK".equals(from), i -> "The scourge of the village has returned. Give him an accounting test!");

    private final Predicate<String> predicate;

    private final Function<Integer, String> function;

    public Predicate<String> getPredicate(a) {
        return predicate;
    }

    public Function<Integer, String> getFunction(a) {
        return function;
    }

    ReturnHomeStrategy(Predicate<String> predicate, Function<Integer, String> function) {
        this.predicate = predicate;
        this.function = function;
    }

    @Override
    public Predicate<String> predicate(a) {
        return this.predicate;
    }

    @Override
    public Function<Integer, String> function(a) {
        return this.function; }}Copy the code

The system runs again as follows

/** * someone goes home **@paramFrom represents the risk coefficient * from the region@paramId worker *@returnTo prove that * /
public String returnHome(String from, Integer id) {
    for (ReturnHomeStrategy value : ReturnHomeStrategy.values()) {
        if (value.predicate().test(from)) {
            returnvalue.function().apply(id); }}throw new RuntimeException("Aliens, catch them and put them in the zoo to sell tickets!");
}
Copy the code

The system finally perfect line, the world is really beautiful, the air is pure and fresh, it is the village I love the floret also was blocked outside the village, is really disconsolate

Serious summary

The author has been thinking about the simplified version of various design patterns, such as the original also wrote the simplified version of the pipeline pattern (don’t go to see, poor thinking, afraid of shame ), this article is also the result of many times of thinking and revision, and I hope you can get some inspiration, so that the design mode is no longer the choice for reconstruction or even restarting the project, and the strategy can be simplified and become a code template that we can use, easy to use and free to use, so as to increase the coding efficiency and embrace a healthy life. Best wishes, thank you!