我是一名初級開發人員(沒有 CS 背景的訓練營),目前從事產品定價作業。我正在向這個偉大的社區尋求建議。
價格基于具有多個級別的 3 個因素:
顏色:白色,藍色,紅色,綠色尺寸:小號,中號,大號材質:棉,絲綢,人造絲
我嘗試過:If-else 控制流程,但知道我們將很快添加更多材料和顏色,這 if else 會更長更慢。
if color == "white" and material == "cotton"
price = 5 if size == "small" || size == "medium"
price = 6 if size == "large"
elsif color == "white" and material == "rayon"
price = 6 if size == "small" || size == "medium"
price = 7 if size == "large"
.
.
.
end
考慮到未來將添加更多級別和因素,定價的最佳實施或方法是什么?
任何將我指向解決方案的建議將不勝感激。
uj5u.com熱心網友回復:
我在這里做出商業假設,但我猜測不同的材料、顏色等會起到價格調節作用。即,給定基礎產品(例如,一件 T 恤),它的基礎價格為 5,然后選擇一些材料/尺寸會增加成本。
如果是這種情況,我可能會建議實作一個PriceModifierPolicy物件,該物件定義常量,并使用傳入的符號 基本價格來“確定”總價格。IE
class PriceModifierPolicy
COLOR_PRICE_MODIFIER_MAP = {
white: 1,
gray: 1,
black: 2
}
MATERIAL_PRICE_MODIFIER_MAP = {
cotton: 0,
rayon: 1
}
SIZE_PRICE_MODIFIER_MAP = {
small: 0,
medium: 0,
large: 1
}
def initialize(base_price, color, material, size)
@base_price = base_price
@color = color
@material = material
@size = size
end
def compute_final_price!
final_price = @base_price color_price_modifier
final_price = material_price_modifier
final_price = size_price_modifier
final_price
end
def color_price_modifier
COLOR_PRICE_MODIFIER_MAP[@color]
end
def material_price_modifier
MATERIAL_PRICE_MODIFIER_MAP[@material]
end
def size_price_modifier
SIZE_PRICE_MODIFIER_MAP[@size]
end
end
這種方法的好處是您可以將 替換為base_price您想要定價的產品,然后將其實作為可繼承的 BasePriceModifierPolicy ,其中包含/可以查詢知識(來自資料庫),關于給定產品的給定定價修飾符。IE
class BasePriceModifierPolicy
COLOR_PRICE_MODIFIER_MAP = {
white: 1,
gray: 1,
black: 2
}
MATERIAL_PRICE_MODIFIER_MAP = {
cotton: 0,
rayon: 1
}
SIZE_PRICE_MODIFIER_MAP = {
small: 0,
medium: 0,
large: 1
}
def initialize(product, color, material, size)
@base_price = product
@color = color
@material = material
@size = size
end
def compute_final_price!
final_price = @base_price color_price_modifier
final_price = material_price_modifier
final_price = size_price_modifier
final_price
end
def color_price_modifier
raise NotImplementedError
end
def material_price_modifier
raise NotImplementedError
end
def size_price_modifier
raise NotImplementedError
end
end
class ShirtPriceModifierPolicy < BasePriceModifierPolicy
COLOR_PRICE_MODIFIER_MAP = {
white: 3,
gray: 2,
black: 5
}
MATERIAL_PRICE_MODIFIER_MAP = {
cotton: 1,
rayon: 2
}
SIZE_PRICE_MODIFIER_MAP = {
small: 1,
medium: 2,
large: 3
}
def color_price_modifier
COLOR_PRICE_MODIFIER_MAP[@color]
end
def material_price_modifier
MATERIAL_PRICE_MODIFIER_MAP[@material]
end
def size_price_modifier
SIZE_PRICE_MODIFIER_MAP[@size]
end
end
如果您不需要支持不同的產品,只需一個不斷擴大的附加組件串列即可。然后檢查裝飾器模式。
uj5u.com熱心網友回復:
我認為除了 oop 的觀點,如果我沒有正確理解你,那么你可以想出一個像這樣的哈希物件:
[
{
color=>"white",
material=>"Cotton",
size=>"medium",
price=>5
}, ...
]
然后通過迭代串列,您可以滿足每個請求的請求,并且將來添加更多引數時,您將不需要更改代碼。但這是最基本的方法,你應該想出一個變體物件然后一個令人滿意的函式來使它更通用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/464554.html
下一篇:如何使用導軌進行接受和拒絕功能
