装饰模式lua实现

装饰模式又名包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。 

Person = {}

Decorator = {}

function Person:new(o)
	o = o or {}
	setmetatable(o,self)
	self.__index = self
	return o;
end

function Person:Show()
	print("我是人")
end

Decorator = Person:new{component = nil}

function Decorator:Decorate(com)
	self.component = com
end

function Decorator:Show()
	print("我是装饰者")
end

Shirt = Decorator:new()


function Shirt:Show()
	print("最后衬衫")
	if self.component ~= nil then
		self.component:Show()
	end
end



Trouser = Decorator:new()

function Trouser:Show()
	print("然后裤子")
	if self.component ~= nil then
		self.component:Show()
	end
end

Shoe = Decorator:new()

function Shoe:Show()
	print("先穿鞋子")
	if self.component ~= nil then
		self.component:Show()
	end
end

person = Person:new()

shirt = Shirt:new()
shirt:Decorate(person)

trouser = Trouser:new()
trouser:Decorate(shirt)

shoe = Shoe:new()
shoe:Decorate(trouser)
shoe:Show()

代码输出:

先穿鞋子
然后裤子
最后衬衫
我是人

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值