Builder Design Pattern like Java and Fluent Interface

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Builder Design Pattern like Java and Fluent Interface

Joao Von
Hello everyone!

This is a Builder Design Pattern like Java, based on Refactoring book from
Martin Fowler. Fluent interface behavior in Lua is easy.


Sincerely yours!

João Von
-----------------------

class = require '30log'

-- Builder Pattern
NutritionFacts = class ('NutritionFacts')
NutritionFacts.servingSize = nil
NutritionFacts.servings = nil
NutritionFacts.calories = nil
NutritionFacts.fat = nil
NutritionFacts.sodium = nil
NutritionFacts.carbohydrate = nil

function NutritionFacts.init (self, builder)
  self.servingSize = builder.servingSize
  self.servings = builder.servings;
  self.calories = builder.calories
  self.fat = builder.fat
  self.sodium = builder.sodium
  self.carbohydrate = builder.carbohydrate
  return self
end

NutritionFactsBuilder = class('Builder')
-- Required parameters
NutritionFactsBuilder.servingSize = nil
NutritionFactsBuilder.servings = nil

-- Optional parameters - initialized to default values
NutritionFactsBuilder.calories = 0
NutritionFactsBuilder.fat = 0
NutritionFactsBuilder.carbohydrate = 0
NutritionFactsBuilder.sodium = 0

function NutritionFactsBuilder.init (self, servingSize, servings)
  self.servingSize = servingSize
  self.servings = servings
end

function NutritionFactsBuilder.calories(self, val)
  self.calories = val; return self end

function NutritionFactsBuilder.fat(self, val)
  self.fat = val; return self end

function NutritionFactsBuilder.carbohydrate(self, val)
  self.carbohydrate = val; return self end

function NutritionFactsBuilder.sodium(self, val)
  self.sodium = val; return self end

function NutritionFactsBuilder.build(self)
  return NutritionFacts:new(self)
end

cocaCola = NutritionFactsBuilder:new(240,8):calories(100):sodium(35):carbohydrate(27):build()

print(cocaCola.calories)