Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcelorxaviers/2e658b6de6a7551417a9f40afdc8907f to your computer and use it in GitHub Desktop.
Save marcelorxaviers/2e658b6de6a7551417a9f40afdc8907f to your computer and use it in GitHub Desktop.
# 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