问题描述
我有一个具有introduced_by
属性的User
模型.根据该属性值,我以不同的方式计算佣金.最好,最灵活的方法是什么?
I have a User
model that has an introduced_by
attribute. Based on that attributes value, I calculate my commission differently. What would be the best, most flexible way of doing this?
我应该进行切换,还是将所有内容都放在一个平面文件中?另外,我应该创建一个Commission
模型吗?
Should I do a switch, or maybe put everything in a flat file? Also, should I create a Commission
model?
推荐答案
这是一个非常广泛的问题,因为没有代码也没有示例.但是,这似乎是Strategy
设计模式的完美案例.
It's a very broad question, as there is no code and no example. However, it seems to be the perfect case of a Strategy
design pattern.
我要做的是创建一个代表每种特定属性值范围策略的类.
What I would do, is to create a class that represents the strategy for every specific range of attribute values.
例如
PersonalCommission
CompanyCommission
HighValueCommission
DefaultCommission
每个类都有一个方法,例如calculate
,您可以调用传递对象的实例并返回佣金的值.
Each class has a single method, let's say calculate
that you can call passing an instance of the object and that returns the value of the commission.
在需要执行计算的任何地方,只需基于User属性初始化一个新的Commission
策略对象,然后在其上调用calculate
.
Wherever you need to perform the calculation, just initialize a new Commission
strategy object based on the User attribute and call calculate
on it.
您甚至不必使用开关,因为您可以动态地初始化类.
You don't even have to use a switch, as you can initialize the class dynamically.
strategy = "#{user.introduced_by}Commission".constantize
strategy.new.compute(whatever)
当然,这只是一个非常简单的示例,您必须适应自己的需求.
Of course, that's just a very simple example you'll have to adapt to your needs.
这篇关于取决于模型属性的业务逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!