Search code examples
grailsstrategy-pattern

Strategy Pattern on Grails


On my current task i have to calculate ideal
This price is calculated by taking all the prices of this product, removing the 2 highest and 2 lowest, then doing an average with the rest and adding 20% to it.

I have my domain class

class Product { 
  String store
  String product_code
  int price
  String notes..........

Its posible to calculate the ideal price using strategy pattern?

enter image description here

How the value ends in the view ?... When the controller work?


Solution

  • Sure, Grails won't stop you from using the strategy pattern. Here's the basic strategy:

    def prices = Product.withCriteria {
        projections {
            property 'price'
        }
    }
    
    def remaining = prices - prices.take(2) - prices.takeRight(2)
    def ideal = remaining.sum() / remaining.size() * 1.2
    

    So it amounts to a GORM query to get the prices, some GDK Iterable methods, and math. You can certainly bundle that up into a strategy pattern, which BTW can be done in Groovy with Closures; you don't need to go the traditional route with interfaces and such:

    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)