标签:lua
-- 加载文件 require "class" ------------------------------ -- 产品 ------------------------------ -- 人类 IHuman = class() function IHuman:Laugh() print("IHuman Laugh") end function IHuman:Cry() print("IHuman Cry") end function IHuman:Talk() print("IHuman Talk") end -- 黄种人 YellowHuman = class(IHuman) function YellowHuman:Laugh() print("黄色人种会哭") end function YellowHuman:Cry() print("黄色人种会大笑,幸福呀") end function YellowHuman:Talk() print("黄色人种会说话,一般说的都是双字节") end -- 白种人 WhiteHuman = class(IHuman) function WhiteHuman:Laugh() print("白色人种会哭") end function WhiteHuman:Cry() print("白色人种会大笑,侵略的笑声") end function WhiteHuman:Talk() print("白色人种会说话,一般都是单字节") end -- 黑种人 BlackHuman = class(IHuman) function BlackHuman:Laugh() print("黑人会哭") end function BlackHuman:Cry() print("黑人会笑") end function BlackHuman:Talk() print("黑人可以说话,一般人听不懂") end --------------- -- 工厂 --------------- IHumanFactory = class() function IHumanFactory:CreateHuman() print("IHumanFactory") end -- 创造黄种人工厂类 YellowHumanFactory = class(IHumanFactory) function YellowHumanFactory:CreateHuman() return YellowHuman:new() end -- 创造白种人工厂类 WhiteHumanFactory = class(IHumanFactory) function WhiteHumanFactory:CreateHuman() return WhiteHuman:new() end -- 创造黑种人工厂类 BlackHumanFactory = class(IHumanFactory) function BlackHumanFactory:CreateHuman() return BlackHuman:new() end -- 测试代码 function DoFactoryMethod(factory) if factory == nil then return end IHuman = factory:CreateHuman() IHuman:Cry() IHuman:Laugh() IHuman:Talk() end --- main --- function main() print("----------第一批人是这样的:黄种人工厂来生产黄种人") DoFactoryMethod(YellowHumanFactory:new()) print("----------第二批人是这样的:白种人工厂来生产白种人") DoFactoryMethod(WhiteHumanFactory:new()) print("----------第一批人是这样的:黑种人工厂来生产黑种人") DoFactoryMethod(BlackHumanFactory:new()) end main()
local _class={} function class(super) local class_type={} class_type.ctor=false class_type.super=super class_type.new=function(...) local obj={} do local create create = function(c,...) if c.super then create(c.super,...) end if c.ctor then c.ctor(obj,...) end end create(class_type,...) end setmetatable(obj,{ __index=_class[class_type] }) return obj end local vtbl={} _class[class_type]=vtbl setmetatable(class_type,{__newindex= function(t,k,v) vtbl[k]=v end }) if super then setmetatable(vtbl,{__index= function(t,k) local ret=_class[super][k] vtbl[k]=ret return ret end }) end return class_type end
版权声明:本文为博主原创文章,未经博主允许不得转载。
设计模式实例(Lua)笔记之一(Factory Method工厂方法模式)
标签:lua
原文地址:http://blog.csdn.net/rexuefengye/article/details/47789085