Created
July 14, 2023 15:51
-
-
Save marcelorxaviers/71a4936997cec5f16b5cd631a9e7739f to your computer and use it in GitHub Desktop.
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
# frozen_string_literal: true | |
# This pattern is often useful in situations where a class cannot anticipate the type of objects it | |
# will need to create, or in situations where a class wants to delegate the responsibility of | |
# creating objects to one of its expert subclasses. | |
# Base class that defines the interface of the object to be created | |
class Car | |
def drive | |
raise NotImplementedError, 'This is an abstract class check one if its subclasses' | |
end | |
end | |
# Subclass that specifies a car model | |
class AmgGt53 < Car | |
def drive | |
puts 'Now we\'re talking... Driving it!' | |
end | |
end | |
# Subclass that specifies a car model | |
class Gle < Car | |
def drive | |
puts 'But why?' | |
end | |
end | |
# The actual car factory class | |
class MercedesBenzFactory | |
def self.create_car(car_type) | |
case car_type | |
when :amg_gt_53 | |
AmgGt53.new | |
when :gle | |
Gle.new | |
else | |
puts "#{car_type.to_s.capitalize} isn't from Mercedes. " \ | |
"And if my grandmother had wheels, she would have been a bike" | |
end | |
end | |
end | |
# Criando um objeto de carro usando a fábrica | |
MercedesBenzFactory.create_car(:gle).drive | |
MercedesBenzFactory.create_car(:amg_gt_53).drive | |
MercedesBenzFactory.create_car(:testarossa) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment