[Java] [Java] Strategy pattern

less than 1 minute read

Verification environment

  • Eclipse Oxygen.3a Release (4.7.3a)
  • Java8

Source code

StrategySample.java


package designpattern;

public class StrategySample {
	public static void main(String[] args) {
		say(new Dog());
		say(new Cat());
	}

	private static void say(Animal animal) {
		animal.say();
	}
}

Dog.java


package designpattern;

public class Dog implements Animal {

	@Override
	public void say() {
		System.out.println("one");
	}

}

Cat.java


package designpattern;

public class Cat implements Animal {

	@Override
	public void say() {
		System.out.println("Meow");
	}

}

Animal.java


package designpattern;

interface Animal {

	void say();
}

Impressions

This is what the Strategy pattern is, right?
This is a code that often appears in the introduction of so-called polymorphism.
This is because I have met many times at work without learning
I could understand it easily.

It’s the same as putting a HashMap in a Map

See you again (^_^) Noshi