设计模式- 装饰者模式 (lua 版本)

实现功能:
张三买手抓饼(令加鸡蛋、火腿)

输出日志:
张三 买了 经典 cake 一份, 一共花了 5 钱
张三 买了 经典 cake 加 Material1 一份, 一共花了 6 钱
张三 买了 经典 cake 加 Material2 一份, 一共花了 7 钱
张三 买了 经典 cake 加 Material1 加 Material2 一份, 一共花了 8 钱
类:
HandCake 、LeeHandCake、Decorator、DecoratorMaterial1、DecoratorMaterial2、DecoratorTest、Costomer
local Costomer = require 'Test/Costomer'
local DecoratorMaterial1 = require 'Test/DecoratorMaterial1'
local DecoratorMaterial2 = require 'Test/DecoratorMaterial2'
local LeeHandCake = require 'Test/LeeHandCake'

---@class DecoratorTest
local class = class()

function class:Start()
    local leeHandCake = LeeHandCake.new()
    local c1 = Costomer.new('张三')

    c1:Buy(leeHandCake)

    local m1 = DecoratorMaterial1.new(leeHandCake)
    c1:Buy(m1)

    local m2 = DecoratorMaterial2.new(leeHandCake)
    c1:Buy(m2)

    c1:Buy(DecoratorMaterial2.new(DecoratorMaterial1.new(leeHandCake)))
end

return class
---@class Costomer
local class = class()

function class:ctor(name)
    self.name = name
end

function class:Name()
    return self.name
end

function class:Buy(cake)
    return log(self.name .. ' 买了 ' .. cake:CakeName() .. ' 一份, 一共花了 ' .. cake:CakeCost() .. ' 钱')
end

return class
---@class HandCake
local class = class()

function class:ctor()

end

function class:CakeName()
    return 'cake name'
end

function class:CakeCost()
    return 3
end

return class
local base = require 'Test/HandCake'

---@class LeeHandCake
local class = class(base)

function class:ctor()
    base.ctor(self)
end

--[[ override ]]--
function class:CakeName()
    return '经典 cake'
end

--[[ override ]]--
function class:CakeCost()
    return 5
end

return class
local base = require 'Test/HandCake'
---@class Decorator
local class = class(base)

function class:ctor(cake)
    base.ctor(self)
    self.cake = cake
end

--[[ override ]]--
function class:CakeName()
    return self.cake:CakeName()
end

--[[ override ]]--
function class:CakeCost()
    return self.cake:CakeCost()
end

return class
local base = require 'Test/Decorator'
---@class DecoratorMaterial1
local class = class(base)

function class:ctor(cake)
    base.ctor(self)
    self.cake = cake
end

--[[ override ]]--
function class:CakeName()
    return self.cake:CakeName() .. ' ' .. '加 Material1'
end

--[[ override ]]--
function class:CakeCost()
    return self.cake:CakeCost() + 1
end

return class
local base = require 'Test/Decorator'
---@class DecoratorMaterial2
local class = class(base)

function class:ctor(cake)
    base.ctor(self)
    self.cake = cake
end

--[[ override ]]--
function class:CakeName()
    return self.cake:CakeName() .. ' ' .. '加 Material2'
end

--[[ override ]]--
function class:CakeCost()
    return self.cake:CakeCost() + 2
end

return class

 

 

 

你可能感兴趣的:(设计模式,lua)