Skip to content

Instantly share code, notes, and snippets.

@Jay-flow
Last active June 21, 2020 06:16
Show Gist options
  • Save Jay-flow/0f664445a7b8e5d4c9d81ba5592ca1c2 to your computer and use it in GitHub Desktop.
Save Jay-flow/0f664445a7b8e5d4c9d81ba5592ca1c2 to your computer and use it in GitHub Desktop.
Strategy pattern
public abstract class Animal {
SwimmingBehavior swimmingBehavior;
SoundBehavior soundBehavior;
public abstarct void display();
public void performSwimming() {
swimmingBehavior.swim();
}
public void performSound() {
soundBehavior.sound();
}
// You can dynamically specify the behavior with the methods below.
public void setSwimmingBehavior(SwimmingBehavior swb) {
swimmingBehavior = swb
}
public void setSoundBehavior(SoundBehavior sb) {
soundBehavior = sb
}
public void breathe() {
System.out.println("All animals breathe.")
}
}
public interface SwimmingBehavior {
public void swim();
}
public class SwimmingWithFeet implements SwimmingBehavior{
public void swim() {
System.out.println("I can swim!");
}
}
public class SwimmingNoWay implements SwimmingBehavior {
public void swim() {
System.out.println("I can't swim")
}
}
public interface SoundBehavior {
public void sound();
}
public class Barking implements SoundBehavior {
public void sound() {
System.out.println("Bow!")
}
}
public class Howling implements SoundBehavior {
public void sound() {
System.out.println("Howl~~~")
}
}
pulic class MuteSound implements SoundBehavior {
public void sound() {
System.out.println("Quiet...")
}
}
public class Dog extends Animal {
public Dong() {
swimmingBehavior = new SwimmingWithFeet();
soundBehavior = new Barking();
}
public void display() {
System.out.println("I'm dog!")
}
}
public class AnimalSimulator {
public static void main(String[] args) {
Animal dog = new Dog();
dog.performSwimming();
dog.performSound();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment