使用元表模拟继承
继承原理: 如果某个成员子类没有, 那就去父类找, 父类没有在往父类找, 直到没有父类
元表原理: 如果某个成员当前对象没有, 就去metatable的__index上找
把两个结合一下: 如果某个成员子类没有, 就去metatable对象的__index上找, 直到没有metatable或metatable对象的__index为nil
1 function class(clsName, superCls) 2 local cls = {} 3 cls.__index = cls 4 cls.__tostring = function(self) 5 if nil ~= self.super then 6 self.super.__tostring(self) 7 end 8 end 9 cls.__clsName = clsName 10 11 if nil ~= superCls then 12 cls.super = superCls 13 if superCls.__index == superCls then 14 setmetatable(cls, superCls) 15 else 16 setmetatable(cls, { __index = superCls }) 17 end 18 else 19 cls.ctor = function() --默认构造函数 20 end 21 end 22 23 cls.new = function(...) 24 local instance = {} 25 setmetatable(instance, cls) 26 instance:ctor(...) 27 return instance 28 end 29 30 return cls 31 end
先定义一个基类:
local Base = class("Base") function Base:ctor(num, str) assert(self.__clsName ~= "Base", "Abstract class can't instance") self.num = num self.str = str end function Base:TestOverride() print(self.__clsName, "Base: TestOverride") end function Base:TestSuper() print(self.__clsName, "Base: TestSuper") end function Base:__tostring() print(self.__clsName, "Base: num:", self.num, "str:", self.str) end
测试1:
1 local A = class("A", Base) 2 function A:TestOverride() 3 print(self.__clsName, "A: TestOverride") 4 end 5 6 function A:TestSuper() 7 self.super.TestSuper(self) 8 print(self.__clsName, "A: TestSuper") 9 end 10 11 function Test1() 12 local a = A.new(5, "A") 13 print("-----") 14 a:TestOverride() 15 print("-----") 16 a:TestSuper() 17 print("-----") 18 tostring(a) 19 end 20 Test1()
运行结果:
A A: TestOverride
-----
A Base: TestSuper
A A: TestSuper
-----
A Base: num: 5 str: A
测试2:
1 local B = class("B", Base) 2 function B:__tostring() 3 print(self.__clsName, "B: num:", self.num, "str:", self.str) 4 end 5 6 7 local B_1 = class("B_1", B) 8 function B_1:TestOverride() 9 print(self.__clsName, "B_1: TestOverride") 10 end 11 12 function B_1:TestSuper() 13 self.super.TestSuper(self) 14 print(self.__clsName, "B_1: TestSuper") 15 end 16 17 18 local B_2 = class("B_2", B) 19 function B_2:TestOverride() 20 print(self.__clsName, "B_2: TestOverride") 21 end 22 23 function B_2:__tostring() 24 print(self.__clsName, "B_2: num:", self.num, "str:", self.str) 25 end 26 27 28 function Test2() 29 local b_1 = B_1.new(3, "B_1") 30 print("-----") 31 b_1:TestOverride() 32 print("-----") 33 b_1:TestSuper() 34 tostring(b_1) 35 36 print("-----") 37 38 local b_2 = B_2.new(4, "B_2") 39 print("-----") 40 b_2:TestOverride() 41 print("-----") 42 b_2:TestSuper() 43 tostring(b_2) 44 end 45 Test2()
运行结果:
B_1 B_1: TestOverride
-----
B_1 Base: TestSuper
B_1 B_1: TestSuper
-----
B_1 B: num: 3 str: B_1
-----
-----
B_2 B_2: TestOverride
-----
B_2 Base: TestSuper
-----
B_2 B_2: num: 4 str: B_2