rubyfactory-patternfactory-method

What is a Ruby factory method?


I understand that a factory method is a class method that utilises the self keyword and instantiates an object of it's own class. I don't understand how this is useful or how it can extend the functionality of initialize method.

I'm working on a project creating a command line address book that asks me to use a factory pattern on the Person class so that I can create a Trainee or Instructor (subclasses) with different attributes.


Solution

  • A factory class is a clean way to have a single factory method that produces various kind of objects. It takes a parameter, a parameter that tells the method which kind of object to create. For example to generate an Employee or a Boss, depending on the symbol that is passed in:

    class Person
      def initialize(attributes)
      end
    end
    
    class Boss
      def initialize(attributes)
      end
    end
    
    class Employee
      def initialize(attributes)
      end
    end
    
    class PersonFactory
      TYPES = {
        employee: Employee,
        boss: Boss
      }
    
      def self.for(type, attributes)
        (TYPES[type] || Person).new(attributes)
      end
    end
    

    and then:

    employee = PersonFactory.for(:employee, name: 'Danny')
    boss = PersonFactory.for(:boss, name: 'Danny')
    person = PersonFactory.for(:foo, name: 'Danny')
    

    I also wrote a more detailed blog post about that topic: The Factory Pattern