Created
April 4, 2023 11:34
-
-
Save marcelorxaviers/2e658b6de6a7551417a9f40afdc8907f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
# The singleton pattern is used when you need to ensure that only one instance of a class exists | |
# and provide a global point of access to it. | |
# | |
# The most common reason to use this design pattern is to control access to some shared resource, | |
# for example a database or a file. | |
# The second most common reason is to create a global variable whose change is more controlled. | |
class TicketDispenserMachine | |
private_class_method :new | |
def initialize | |
@ticket_number = 0 | |
end | |
def self.instance | |
@instance ||= new | |
end | |
def take | |
"Your ticket is ##{@ticket_number}".tap { @ticket_number += 1 } | |
end | |
end | |
TicketDispenserMachine.instance.take | |
TicketDispenserMachine.new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment