Is the strategy in the strategy pattern always an interface? What pattern would it be when the strategy is abstract?

有帮助吗?

解决方案

Is the strategy in the strategy pattern always an interface?

That depends on what you mean by "interface". If you mean the standard general programming meaning of "an abstraction that hides its details" that is used in such words as "User Interface (UI)", "Application Programming Interface (API)", "Application Binary Interface (ABI)", "Network Interface", "Audio Interface" and so on, then yes, it is always an interface. That is, after all, the whole point of the Strategy Pattern.

If you mean the specific Java / C♯ interface keyword, then no, obviously not, since it doesn't even exist in the overwhelming majority of languages.

What pattern would it be when the strategy is abstract?

Strategy.

There is no mention of interface on the Strategy Pattern page of the Portland Pattern Repository on Ward's Wiki, nor is there any mention of it in the "Gang of Four Book" (Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm).

其他提示

The strategy pattern is rather orthogonal with regards to the language-specific construct of an interface. The strategy pattern works just fine in languages which do not have an interface or equivalent keyword.

This is especially true for dynamically typed languages like Python where its pointless/meaningless to define an interface as a construct; objects in those languages have dynamic structures, so the interfaces to those objects are also dynamic.

In the case of a language such as C++, defining an interface is achieved using class or struct keywords; creating a class/struct which only declares pure-virtual member functions.

The Strategy (as defined in the GoF book) is an interface in the sense that it defines an API: a common way to access different ConcreteStrategy implementations.

How you implement this conceptual idea of an interface depends entirely on your programming language. For example Java has an interface as a separate language construct, C++ does not. Actually the GoF book has an example C++ implementation that passes the concrete type of the used strategy implementation as a template parameter, completely eliminating an explicit Strategy interface.

The point is, the choice between interface and abstract class (if at all possible) is an implementation detail. It does not affect the strategy pattern in any way.

许可以下: CC-BY-SA归因
scroll top