Skip to content

Instantly share code, notes, and snippets.

@cesartalves
Last active January 27, 2021 22:05
Show Gist options
  • Save cesartalves/ee588a64db32d233ac24369efbfade07 to your computer and use it in GitHub Desktop.
Save cesartalves/ee588a64db32d233ac24369efbfade07 to your computer and use it in GitHub Desktop.
class NilObjectUnderstadingStrategy
def self.can_talk_to?(character)
true
end
end
class HumanCharacterUnderstandingStrategy
def self.can_talk_to?(character)
character.is_a? Human
end
end
class AlienAndHumanCharacterUnderstandingStrategy
def self.can_talk_to?(character)
HumanUnderstandingStrategy.can_talk_to?(character) ||
AlienUnderstandingStrategy.can_talk_to?(character)
end
end
class Alien
# yes, my variable names are very long :-
def initialize(character_understading_strategy:, others:)
@strategy = character_understanding_strategy
# your standard initialization code
end
def can_talk_to?(character)
@strategy.can_talk_to? character
end
end
# example usage
# level 0
Alien.new(HumanCharacterUnderstandingStrategy)
# level 2
Alien.new(AlienAndHumanCharacterUnderstandingStrategy)
# polyglot alien no problem
Alien.new(NilObjectUnderstadingStrategy)
# git commit -m "feature/13233-make-alien-talk-to-itself: injects characters alien can talk to in initializer"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment