首页 > 代码库 > lua类库 middleclass学习笔记

lua类库 middleclass学习笔记

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

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

local class = require middleclass--类的继承Person = class(Person)  --定义一个Person类function Person:initialize(name)  --构造函数    self.name = nameendfunction Person:speak() --方法    print("Hi,i am " ..self.name .. ".")endAgedPerson = class(AgedPerson,Person) --子类AgedPerson.static.ADULT_AGE = 18  --类成员function AgedPerson:initialize(name,age)  --子类构造    Person.initialize(self,name)    self.age = ageendfunction AgedPerson:speak()  --子类方法    Person.speak(self)   --子类调用父类方法    if(self.age < AgedPerson.ADULT_AGE) then        print("i am underaged")    else        print("i am an adult")    endendlocal 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")    endendfunction DrinksCoffe:include(klass)    print(klass.name .. " drinks coffee at " .. klass.coffeeTime)endEnglishMan = class(EnglishMan)EnglishMan.static.coffeeTime = 5EnglishMan:include(DrinksCoffe)function EnglishMan:initialize(name) self.name = name endSpaniard = class(Spaniard)Spaniard.static.coffeeTime = 6Spaniard:include(DrinksCoffe)function Spaniard:initialize(name) self.name = name endtom = 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 = yendfunction Point:__tostring()    return Point:[ .. tostring(self.x) .. , .. tostring(self.y) .. ]endp1 = Point(100,200)print(p1)