Last active
December 20, 2015 03:59
-
-
Save jasonblanchard/6067429 to your computer and use it in GitHub Desktop.
Dependency Injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Animal | |
def initialize | |
@sound = "Crickets, crickets..." | |
end | |
def make_noise | |
puts @sound | |
end | |
end | |
class Dog < Animal | |
def initialize | |
@sound = "Woof, woof" | |
end | |
end | |
class Cat < Animal | |
def initialize | |
@sound = "Meow, puurrr" | |
end | |
end | |
class Cow < Animal | |
def initialize | |
@sound = "Moooo" | |
end | |
end | |
class PetAnimal | |
def initialize(animal = Animal.new) | |
@animal = animal | |
end | |
def pet | |
@animal.make_noise | |
end | |
end | |
PetAnimal.new.pet # "Crickets, crickets..." | |
PetAnimal.new(Dog.new).pet # "Woof, woof" | |
PetAnimal.new(Cat.new).pet # "Meow, puurrr" | |
PetAnimal.new(Cow.new).pet # "Moooo" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment