Using an abstract class instead of an interface in the strategy design pattern

I'm just learning Java and design patterns and trying to figure out when to use interfaces and abstract classes. I am wondering in the Strategy design pattern, why is it preferable to use an interface for behavior / algorithm subclasses rather than an abstract superclass?

Is it simply because there is no need for an abstract class, because each behavior / algorithm subclass has its own implementation, and so the abstract superclass will just provide additional functionality that will not be used?

Wouldn't an abstract class mean that there is an additional option to use this additional functionality in the future if needed, such as adding a method to the abstract superclass that is shared by the behavior / algorithm subclasses if needed. Is there a reason why this is a bad idea?

Or is there another reason?

+3


source to share


4 answers


You should use a common interface for all your strategies and also create an abstract class that implements it. So, even though all your strategies currently share an abstract class, your system is expanding because you can create unrelated strategies for that abstract in the future.

Now using only some of the superclass methods is a decision you have to make. It may or may not be worthy.



note :: If you are using something similar to the template template you should check how to use hooks.

+4


source


Prior to Java 8, interfaces had one big problem: it was impossible to add additional functionality (that is, add new methods) without breaking any implementation of that interface. Abstract base classes were a way to avoid this problem.



Java 8 introduced default methods that basically solve this problem. Thus, thanks to the modern Java system, interfaces provide much more flexibility without disadvantages.

+1


source


From an implementation point of view, you can use both an interface and an abstract class. The difference lies in the purpose of use.

  • The main purpose of interfaces is to provide methods (i.e. communication points) to other classes. That is, dependency decoupling and inversion.
  • The main purpose of abstract classes is to help you inherit the inheritance structure.

In a strategy pattern, this means that if you use AbstractState to define a common code base, you can still wrap the IState interface between Context and AbstractState to separate them more.

+1


source


There is no hard and fast rule between interface or abstract pattern. Use whichever is best for your situation.

If you have multiple strategy implementations that are very similar, you can use abstract classes or even a subclass of one of the strategies.

0


source







All Articles