jeudi 27 août 2015

Ruby - Method Factory

I have being reading about Factory Method Pattern and I still having trouble to understand how to use in practical cases even after reading examples and questions about it.

For example suppose a case where there is two ways to getting data into my class i.e the user input can be either:

Name Surname

Surname, Name

This is something that I would solve more or less like this:

class Name
  attr_accessor :name
  attr_accessor :surname
  def initialize(rawname)
    if(rawname.include? ',')
      @name = rawname.split(', ').last
      @surname = rawname.split(', ').first
    else
      @name = rawname.split(' ').first
      @surname = rawname.split(' ').last
    end
  end
  def print
    puts "#{@name} #{@surname}"
  end
end

How should I implement Factory method on this example? Or in general, how should my though process be in order to use such design patterns?

Aucun commentaire:

Enregistrer un commentaire