Ruby - 方法工厂

Ruby - Method Factory

我正在阅读有关 Factory Method Pattern and I am still having trouble understanding how to use it in practical cases even after reading examples and questions 的内容。

例如,假设有两种方法可以将数据输入我的 class,即用户输入可以是:

Name Surname

Surname, Name

这是我或多或少会像这样解决的问题:

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

我应该如何在这个例子中实现工厂方法?或者一般来说,我应该如何使用这样的设计模式?

这不是最优的,但你可以先规范化原始名称。

class Name
  attr_accessor :name, :surname
  def initialize(rawname)
    @name, @surname = rawname.split(", ").rotate.join(" ").split
  end
end

我应该如何在这个例子中实现工厂方法?

你不应该。

In class-based programming, the factory method pattern is a creational pattern which uses factory methods to deal with the problem of creating objects without specifying the exact class of object that will be created.

当您拥有 Name 的专门子 class 时,那么也许。

为了使用这样的设计模式,我的思维过程应该如何?

您的第一个想法应该是“这个模式在这里有意义吗?我是否足够了解这个模式以尝试在这里应用它?”。如果答案是“是”和“是”,那么你就应用它。

更新:

您最有可能在这里使用的是Factory pattern

In class-based programming, a factory is an abstraction of a constructor of a class

class NameFactory
  def self.create(str)
    # break str here
    Name.new(first_name, last_name)
  end
end

# then

@user.name = NameFactory.create(params[:user_name])

在这个具体的例子中,在现实生活中,我不会使用任何工厂的东西。这只是不必要的并发症。但是,如果我有一个明显更复杂的 class(比如 Transaction),那么我会采用某种创建模式,是的。通常是 Builder.