Lua面向对象 --- 多态
多态,简单的理解就是事物的多种形态。专业的术语说就是:同一个实现接口,使用不同的实例而执行不同的操作。
工程结构:
BaseRoom.lua:
1 BaseRoom = {} 2 3 function BaseRoom:new() 4 self = {} 5 setmetatable(self,BaseRoom) 6 BaseRoom.__index = BaseRoom 7 return self 8 end 9 10 --对该方法的调用体现了多态 11 function BaseRoom:Size() 12 return 100 13 end 14 15 function BaseRoom:GetSize() 16 return self:Size()*2 17 end 18 19 return BaseRoom
MarryRoom.lua:
1 require "BaseRoom" 2 3 MarryRoom = {} 4 5 function MarryRoom:new() 6 setmetatable(MarryRoom, BaseRoom) 7 BaseRoom.__index = BaseRoom 8 9 self = {} 10 setmetatable(self,MarryRoom) 11 MarryRoom.__index = MarryRoom 12 13 return self 14 end 15 16 --对该方法的调用提现了多态 17 function MarryRoom:Size() 18 return 50 19 end 20 21 return MarryRoom
StarRoom.lua:
1 require "BaseRoom" 2 3 StarRoom = {} 4 5 function StarRoom:new() 6 setmetatable(StarRoom,BaseRoom) 7 BaseRoom.__index = BaseRoom 8 9 self = {} 10 setmetatable(self,StarRoom) 11 StarRoom.__index = StarRoom 12 13 return self 14 end 15 16 --对该方法的调用体现了多态 17 function StarRoom:Size() 18 return 20 19 end 20 21 return StarRoom
码云上的相关工程:https://gitee.com/luguoshuai/LearnLua