What is the name of the Design pattern to turn a Product into a LineItem?
Maybe there are several, if so, what are the names of them?
(examples are in Ruby)
Making Product responsible for converting:
class Product
attr_accessor :price
def to_line_item
LineItem.new(price: self.price)
end
end
class LineItem
attr_accessor :price
end
product = Product.new
product.price = 12.00
line_item = product.to_line_item
line_item.price #=> 12.00
Making LineItem responsible for converting:
class Product
attr_accessor :price
end
class LineItem
attr_accessor :price
def from_product(product)
self.new(price: product.price)
end
end
product = Product.new
product.price = 12.00
line_item = product.to_line_item
line_item.price #=> 12.00
Having an intermediate (Factory?) convert:
class Product
attr_accessor :price
end
class LineItem
attr_accessor :price
end
class LineItemBuilder
def self.create(product)
LineItem.new(price: product.price)
end
end
product = Product.new
product.price = 12.00
line_item = LineItemBuilder.create(product)
line_item.price #=> 12.00
Which of these three are the most common implemented to create a Foo from a Bar?
Two notes:
- In our case, the mapping from Product to Line Item is a tad more complex: more attributes (which don't always map 1-to-1 in both classes)
- LineItem gets fed not just product, but some additional attributes (
:user_provided_note, for example)
Aucun commentaire:
Enregistrer un commentaire