From c266a0c3f9f2380e241e551a1b732882d5474528 Mon Sep 17 00:00:00 2001 From: bethrobson Date: Wed, 14 Jul 2021 08:22:44 -0700 Subject: [PATCH] Adding code for Animals in Chapter 1 --- .../designpatterns/strategy/AnimalTest.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/headfirst/designpatterns/strategy/AnimalTest.java diff --git a/src/headfirst/designpatterns/strategy/AnimalTest.java b/src/headfirst/designpatterns/strategy/AnimalTest.java new file mode 100644 index 00000000..b74481c6 --- /dev/null +++ b/src/headfirst/designpatterns/strategy/AnimalTest.java @@ -0,0 +1,40 @@ +package headfirst.designpatterns.strategy; + +import java.util.ArrayList; + +public class AnimalTest { + + public static void main(String[] args) { + AnimalTest at = new AnimalTest(); + at.makeSomeAnimals(); + } + public void makeSomeAnimals() { + Animal dog = new Dog(); + Animal cat = new Cat(); + // treat dogs and cats as their supertype, Animal + ArrayList animals = new ArrayList(); + animals.add(dog); + animals.add(cat); + animals.forEach(Animal::makeSound); // can call makeSound on any Animal + } + + public abstract class Animal { + abstract void makeSound(); + } + public class Dog extends Animal { + void makeSound() { + bark(); + } + void bark() { + System.out.println("Woof"); + } + } + public class Cat extends Animal { + void makeSound() { + meow(); + } + void meow() { + System.out.println("Meow"); + } + } +}