1. 程式人生 > 實用技巧 >lua 面向物件筆記 繼承 和 組合

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