This Java example demonstrates a simple implementation of the Strategy Design Pattern.
It defines different moving strategies for a "Hero" character and allows the user to choose and apply different strategies.
move()
: This interface defines amove
method for different moving strategies.
move()
: Implements themove
method for walking.
move()
: Implements themove
method for flying in a plane.
move()
: Implements themove
method for riding a horse.
move()
: Implements themove
method for driving a car.
setMovingStrategy(MovingStrategy someStrategy)
: Sets the moving strategy for the Hero.move()
: Invokes themove
method based on the current strategy.
To use this example, you can follow these steps:
- Create a
Hero
instance. - Set the moving strategy using
setMovingStrategy(MovingStrategy someStrategy)
. - Invoke the
move
method on theHero
to perform the chosen strategy.
Here are some example usages:
Hero hero = new Hero();
hero.setMovingStrategy(new Walking());
hero.move(); // Outputs: Walking...
hero.setMovingStrategy(new CarDriving());
hero.move(); // Outputs: Driving a car...
You can run the provided Main class to interactively choose different strategies.