Additional Java Interfaces

I have an interface like this:

public interface Foo<T> {
    default void doStuff(T val1, T val2) {}

    default void doStuff(T val) {}
}

The idea of ​​an interface is that you can implement one or other methods. So I have an abstract class:

abstract public class AbstractFoo<T> implements Foo<T> {
    //Bunch of Stuff
}

And finally, such an implementation:

public class AwesomeOne extends AbstractFoo<String> {
    @Override
    public void doStuff(String val) {
        //Do Stuff
    }
}

Here is an example of another implementation:

public class AwesomeTwo extends AbstractFoo<String> {
    @Override
    public void doStuff(String val1, String val2) {
        //Do Stuff
    }
}

This works great. Now I want to specify two different types for the method doStuff(val1, val2). So I would like to do something like this:

public class AwesomeThree extends AbstractFoo<String, Double> {
    @Override
    public void doStuff(String val1, Double val2) {
        //Do Stuff
    }
}

So my interface will change:

public interface Foo<S, T> {
    default void doStuff(S val1, T val2) {}

    default void doStuff(T val) {}
}

But I can hardly get the abstract class to work with this. Because, although I can change my abstract class to this:

abstract public class AbstractFoo<S, T> implements Foo<S, T> {
    //Bunch of Stuff
}

This would change the implementation classes as follows:

public class AwesomeOne extends AbstractFoo<Object, String> {
    @Override
    public void doStuff(String val) {
        //Do Stuff
    }
}

What works, but ... this is not a completely clean solution. It will also force me to reorganize all existing implementations.

Mostly in plain English, I want to say:

Foo , . , doStuff (T val), 1 . , , , doStuff (S val1, T val2), .

Java, , ?

+4
1

OO, .

, " ", . "" .

, , :

public interface StuffDoer {
  void run();
}

. . , , 1- 2-arg. StuffDoer run(). ? .

public abstract class OneArgStuffDoer<T1> implements StuffDoer {
  private final T1 arg;
  public OneArgStuffDoer(T1 arg) {
    this.arg = Objects.requireNonNull(arg);
  }
  public final void run() {
    run(arg);
  }
  abstract void run(T1 arg);
}

TwoArgStuffDoer. API OneArgStuffDoer, TwoArgStuffDoer, run(T1 arg) , run(T1 arg1, T2 arg2) .

AwesomeOne :

public final class AwesomeOne extends OneArgStuffDoer<String> {
  @Override
  void run(String str) { // do your awesome stuff here }
}

! !?!

, !

+4

Source: https://habr.com/ru/post/1696080/


All Articles