|
- --[[-- 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 = false
- class_type.__delete = false
- class_type.__cname = classname
- class_type.__ctype = ClassType.class
-
- class_type.super = super
- class_type.New =function(...)-- 生成一个类对象
- local obj ={}
- obj._class_type = class_type
- obj.__ctype = ClassType.instance
-
- -- 在初始化之前注册基类方法
- setmetatable(obj,{
- __index = _class[class_type],})-- 调用初始化方法
- do
- local create
- create =function(c,...)if c.super then
- create(c.super,...)
- end
- if c.__init then
- c.__init(obj,...)
- end
- end
- create(class_type,...)
- end
- -- 注册一个delete方法
- obj.Delete =function(self)if self.__isDeleted then
- Logger.LogError(string.format("Trying to delete object which was already deleted. %s", table.dump(self)));return;
- end
- if(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 doif now_super.__delete then
- now_super.__delete(self)
- end
- now_super = now_super.super
- end
- self.__isDeleting = nil;
- self.__isDeleted = true;
- end
- obj.GetClassType =function(self)return self._class_type;
- end
- obj.IsAlive =function(self)return not self:IsDeleting() and not self:IsDeleted();
- end
- obj.IsDeleting =function(self)return self.__isDeleting;
- end
- obj.IsDeleted =function(self)return self.__isDeleted;
- end
- if(DebugManager ~= nil and DebugManager:LogCreateCall())then
- Logger.Log(" Create : "..tostring(obj).."\n"..truncate(table.dump(obj),1024))
- end
- return obj
- end
- local vtbl ={}assert(_class[class_type]== nil,"Aready defined class : ", classname)
- _class[class_type]= vtbl
- _className[classname]= class_type
- setmetatable(class_type,{
- __newindex =function(t,k,v)
- vtbl[k]= v
- end
- ,--For call parent method
- __index = vtbl,})if super then
- setmetatable(vtbl,{
- __index =function(t,k)
- local ret = _class[super][k]--do not do accept, make hot update work right!--vtbl[k]= ret
- return ret
- end
- })
- end
-
- return class_type
- end
- function Class(className)return _className[className];
- end
复制代码 当你需要继承的时候可以使用- local UIOperateTipPanel =BaseClass("UIOperateTipPanel", UIBaseView)
复制代码 |
|