lua类库 middleclass学习笔记

middleclass使在lua中面象对象变的简单

抄了一遍他的示例代码运行着试了试,基本懂了

local class = require 'middleclass'

--类的继承
Person = class('Person')  --定义一个Person类
function Person:initialize(name)  --构造函数
    self.name = name
end

function Person:speak() --方法
    print("Hi,i am " ..self.name .. ".")
end

AgedPerson = class('AgedPerson',Person) --子类
AgedPerson.static.ADULT_AGE = 18  --类成员

function AgedPerson:initialize(name,age)  --子类构造
    Person.initialize(self,name)
    self.age = age
end

function AgedPerson:speak()  --子类方法
    Person.speak(self)   --子类调用父类方法
    if(self.age < AgedPerson.ADULT_AGE) then
        print("i am underaged")
    else
        print("i am an adult")
    end
end

local p1 = AgedPerson:new('张东升',13) --定义一个子类对象
local p2 = AgedPerson:new('无量',21)
p1:speak()



--Mixins 这种特性可以在不同的类之间共享一些函数,
--可以是不同的基类
HasWings =
{
    fly = function(self)
        print('flap flap i am a ' .. self.class.name)
    end
}

Animal = class('Animal')  --动物类
Insect = class('Insect',Animal)  --昆虫类
Worm = class('Worm',Insect) --虫子
Bee = class('Bee',Insect) --蜜蜂
Bee:include(HasWings) --增加类成员
Mammal = class('Mammal',Animal) --哺乳动物
Fox = class('Fox',Mammal) --狐狸
Bat = class('Bat',Mammal) --蝙蝠
Bat:include(HasWings) --

local bee = Bee()
local bat = Bat()
bee:fly()
bat:fly()




--下在这种方法
DrinksCoffe = {}
function DrinksCoffe:drink(drinkTime)
    if drinkTime ~= self.class.coffeeTime then
        print(self.name .. ": It is not the time to drink coffee")
    else
        print(self.name .. ": Mmm I love coffee ad drinkTime")
    end
end

function DrinksCoffe:include(klass)
    print(klass.name .. " drinks coffee at " .. klass.coffeeTime)
end

EnglishMan = class('EnglishMan')
EnglishMan.static.coffeeTime = 5
EnglishMan:include(DrinksCoffe)
function EnglishMan:initialize(name) self.name = name end

Spaniard = class('Spaniard')
Spaniard.static.coffeeTime = 6
Spaniard:include(DrinksCoffe)
function Spaniard:initialize(name) self.name = name end

tom = EnglishMan:new('tom')
juan = Spaniard:new('juan')
tom:drink(5)
juan:drink(5)
juan:drink(6)



--为类增加元方法
Point = class('Point')
function Point:initialize(x,y)
    self.x = x
    self.y = y
end

function Point:__tostring()
    return 'Point:[' .. tostring(self.x) .. ',' .. tostring(self.y) .. ']'
end
p1 = Point(100,200)
print(p1)

 

posted @ 2014-08-14 15:13  瓜蛋  阅读(3210)  评论(0编辑  收藏  举报