--[[
-- Lua面向对象设计
--]]--保存类类型的虚表
local _class = {
}
local _className = {
} ClassType = {
class = 1,instance = 2,
}function BaseClass(classname, super)assert(type(classname) == "string" and #classname > 0)-- 生成一个类类型local class_type = {
}-- 在创建对象的时候自动调用class_type.__init = falseclass_type.__delete = falseclass_type.__cname = classnameclass_type.__ctype = ClassType.classclass_type.super = superclass_type.New = function(...)-- 生成一个类对象local obj = {
}obj._class_type = class_typeobj.__ctype = ClassType.instance-- 在初始化之前注册基类方法setmetatable(obj, {
__index = _class[class_type],})-- 调用初始化方法dolocal createcreate = function(c, ...) if c.super thencreate(c.super, ...)endif c.__init thenc.__init(obj, ...)end endcreate(class_type, ...)end-- 注册一个delete方法obj.Delete = function(self)if self.__isDeleted thenLogger.LogError(string.format("Trying to delete object which was already deleted. %s", table.dump(self)));return;endif(DebugManager ~= nil and DebugManager:LogDeleteCall())then Logger.Log(" Delete self : " .. tostring(self) .. "\n" .. truncate(table.dump(self), 1024))end self.__isDeleting = true;local now_super = self._class_type while now_super ~= nil do if now_super.__delete thennow_super.__delete(self)endnow_super = now_super.superendself.__isDeleting = nil;self.__isDeleted = true;endobj.GetClassType = function(self)return self._class_type;endobj.IsAlive = function(self)return not self:IsDeleting() and not self:IsDeleted();endobj.IsDeleting = function(self)return self.__isDeleting;end obj.IsDeleted = function(self)return self.__isDeleted;endif(DebugManager ~= nil and DebugManager:LogCreateCall())then Logger.Log(" Create : " .. tostring(obj) .. "\n" .. truncate(table.dump(obj), 1024))endreturn objendlocal vtbl = {
}assert(_class[class_type] == nil, "Aready defined class : ", classname)_class[class_type] = vtbl_className[classname] = class_typesetmetatable(class_type, {
__newindex = function(t,k,v)vtbl[k] = vend, --For call parent method__index = vtbl,})if super thensetmetatable(vtbl, {
__index = function(t,k)local ret = _class[super][k]--do not do accept, make hot update work right!--vtbl[k] = retreturn retend})endreturn class_type
endfunction Class(className)return _className[className];
end
当你需要继承的时候可以使用
local UIOperateTipPanel = BaseClass("UIOperateTipPanel", UIBaseView)