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)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值