Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement BiFunctional function that corresponds to Enum in Java?

I have Java enum:

public enum ConflictResolutionStrategy {
    softResolve,
    hardResolve,
}

I want to call it like ConflictResolutionStrategy.hardResolve.apply(case1, case2).

Both case1 and case2 objects of the same type. apply in my case should return nothing.

The basic idea behind this design. Create Strategy design pattern and resolve conflicts based on the set enum value.

I cannot find any similar questions on StackOveflow even simple search gives me tons of similar cases which don't resolve my case directly.

I tried The following:

public enum ConflictResolutionStrategy {
    softResolve ((CaseType case1, CaseType case2) -> case1.update(case2)),
    hardResolve,
}

This version above doesn't compile.

I tried another solution:

public enum ConflictResolutionStrategy {
    softResolve,
    hardResolve {
        public void apply(CaseType case1, CaseType case2) {
            case1.update(case2);
        }
    },
}

The second solution, works okay but requires too much code.

like image 758
Dmytro Chasovskyi Avatar asked Feb 05 '19 14:02

Dmytro Chasovskyi


1 Answers

A function accepting two parameters and returning nothing is a BiConsumer.

Your enum may implement BiConsumer:

public enum ConflictResolutionStrategy implements BiConsumer<CaseType, CaseType> {
    softResolve ((case1, case2) -> case1.update(case2)),
    hardResolve((case1, case2) -> {/* do something else */});

    private final BiConsumer<CaseType, CaseType> consumer;

    ConflictResolutionStrategy(BiConsumer<CaseType, CaseType> consumer){
        this.consumer = consumer;
    }

    @Override
    public void accept(CaseType case1, CaseType case2) {
        consumer.accept(case1, case2);
    }

}

Suppose you have a method for processing your cases:

public void processCases(Collection<CaseType> cases, BiConsumer<CaseType, CaseType> conflictResolutionStrategy){
    // ...
}

Now you can pass in either one of your existing strategies:

processCases(cases, ConflictResolutionStrategy.softResolve);

or an inline strategy:

processCases(cases, (c1, c2) -> { /* do smth here */ }); 
like image 196
ETO Avatar answered Sep 18 '22 06:09

ETO