Grails 上的策略模式
Strategy Pattern on Grails
在我当前的任务中,我必须计算理想值
这个价格的计算方法是取该产品的所有价格,去掉最高的 2 个和最低的 2 个,然后对其余的进行平均,然后再加上 20%。
我有我的域名class
class Product {
String store
String product_code
int price
String notes..........
是否可以使用策略模式计算理想价格?
值如何在视图中结束?...当控制器工作时?
当然,Grails 不会阻止您使用策略模式。这是基本的 策略:
def prices = Product.withCriteria {
projections {
property 'price'
}
}
def remaining = prices - prices.take(2) - prices.takeRight(2)
def ideal = remaining.sum() / remaining.size() * 1.2
所以它相当于 GORM query to get the prices, some GDK Iterable 方法和数学。您当然可以将其捆绑到一个策略模式中,BTW 可以在 Groovy 中使用闭包完成;你不需要走传统的接口路线,比如:
def idealPriceStrategy = { prices ->
def remaining = prices - prices.take(2) - prices.takeRight(2)
return remaining.sum() / remaining.size() * 1.2
}
def myStrategy = idealPriceStrategy
def ideal = myStrategy(prices)
在我当前的任务中,我必须计算理想值
这个价格的计算方法是取该产品的所有价格,去掉最高的 2 个和最低的 2 个,然后对其余的进行平均,然后再加上 20%。
我有我的域名class
class Product {
String store
String product_code
int price
String notes..........
是否可以使用策略模式计算理想价格?
值如何在视图中结束?...当控制器工作时?
当然,Grails 不会阻止您使用策略模式。这是基本的 策略:
def prices = Product.withCriteria {
projections {
property 'price'
}
}
def remaining = prices - prices.take(2) - prices.takeRight(2)
def ideal = remaining.sum() / remaining.size() * 1.2
所以它相当于 GORM query to get the prices, some GDK Iterable 方法和数学。您当然可以将其捆绑到一个策略模式中,BTW 可以在 Groovy 中使用闭包完成;你不需要走传统的接口路线,比如:
def idealPriceStrategy = { prices ->
def remaining = prices - prices.take(2) - prices.takeRight(2)
return remaining.sum() / remaining.size() * 1.2
}
def myStrategy = idealPriceStrategy
def ideal = myStrategy(prices)