A method has two parts: an operation (prototype, header) and an implementation:
Method = Operation + Implementation
For example:
public void deposit(double amt) // the operation
{ balance += amt; } // the
implementation
An interface specifies what operations an implementing class should implement.
A class declaration binds (associates) operations to implementations.
Since classes are declared when they are loaded, this binding can't change dynamically.
We can't "assign" a new implementation to an operation the way we can assign a new value to a field.
The Strategy Design Pattern allows us to decouple the implementations and operations.
Here's how we employ this pattern in UW 4.0:
The implementation can be found in:
We have accomplished what we set out to accomplish. Notice that in Tournament.main we have three instances of Character: itch, scratch, and crusty. These are not instances of Character subclasses. Indeed, there are no Character subclasses. And yet, each uses a different implementation of attack.
To put it another way, we have decoupled identity from behavior.
The Bridge Design Pattern allows us to place the algorithms used by all of a classes' methods into a single implementor object, thus decoupling abstraction/identity from implementation at the class level:
We still have a hierarchy to maintain. This time instead of maintaining a hierarchy of characters, we must maintain a hierarchy of strategies.
This pattern can only be used if we are implementing the Character class. What if the Character class has already been implemented and can't be changed?