lua 面向对象笔记 继承 和 组合

-- functions.lua
function
class(classname, super) local superType = type(super) local cls

if superType ~= "function" and superType ~= "table" then superType = nil super = nil end if superType == "function" or (super and super.__ctype == 1) then -- inherited from native C++ Object cls = {}
if superType == "table" then -- copy fields from super for k,v in pairs(super) do cls[k] = v end cls.__create = super.__create cls.super = super else cls.__create = super cls.ctor = function() end end cls.__cname = classname cls.__ctype = 1 function cls.new(...) local instance = cls.__create(...) -- copy fields from class to native object for k,v in pairs(cls) do instance[k] = v end instance.class = cls instance:ctor(...) return instance end else -- inherited from Lua Object if super then cls = {} setmetatable(cls, {__index = super}) cls.super = super else cls = {ctor = function() end} end cls.__cname = classname cls.__ctype = 2 -- lua cls.__index = cls function cls.new(...) local instance = setmetatable({}, cls) instance.class = cls instance:ctor(...) return instance end end return cls end

- 两个类组合

1、创建class room 只需要require  functuins.lua 即可

require "functions"
local room = class("room")

function room:ctor(room_id)
    -- 需要的变量
    local success, room_sink_creator = pcall(require, "room_sink") 
    if success then
        self.sink = room_sink_creator.new(self) -- 把self传入
    end
end

-- 这里就可以调用 self.sink:function
function room:test_sink_func()
    if self.sink and self.sink.func then
        self.sink:func()
    end
end
function
room:func()
  print("room func call")
end

2、创建class room_sink 

require "functions"

local room_sink = class("room_sink")

function room_sink:ctor(room)
    self.room = room
    -- 其他数据    
end

function room_sink:func()
    print("room_sink func() call")
end

-- 这里可以调用 room里的方法
function room_sink:test_room_func()
     self.room:func()   
end

这里创建了两个类 room 和 room_sink,这里有一个很特殊的地方,room可以调用room_sink 的方法,同时room_sink 也可以调用room的方法。(这里room和room_sink 并不是继承关系 而是组合)

- 继承

1、创建基类 room

require "functions"
local room = class("room")

function room:ctor(room_id)
    -- 需要的变量
    self.room_id = room_id
end

function room:func()
  print("room func call")
end

2、创建派生类

require "functions"

local room = require "room"
local room_sink = class("room_sink", room)

function room_sink:ctor(room)
    self.room = room
    -- 其他数据    
end

-- 重写基类方法
function room_sink:func()
    print("room_sink func() call")
end

 

posted @ 2020-11-25 14:50  低调小怪  阅读(188)  评论(0编辑  收藏  举报