设计模式是什么?
设计模式主要更好地解决几个问题:开发时的耦合性、可维护性、可扩展性、可移植性。
1、开发时的耦合性:由于一个大型项目不可能由一个人完全开发,这里为了能够很好的并行开发,不会出现等待别人开发完毕才能够开发的情况,良好的设计模式可以起到很好的作用。
2、可维护性:在一个项目后面更新迭代中可能会出现很多需求的更改,那么良好的设计模式将帮助你更快速的维护。
3、可扩展性:同上,一个项目只要还在使用,就会不断地扩展新功能,好的设计模式可以不用在对原来的结构大动干戈的情况下添加新的功能。
4、可移植性:良好的架构和设计模式让程序可读性更好,在移植到一个新平台上或者使用新的技术移植时将减少错误率。
那么设计模式究竟是什么?
假如你在大街上走着路,很拥挤,这个时候前面的人说你踩到他了,你说并没有,最终吵了一顿或者打了一架才解决,各自散去。
如果这是一个程序,那么这个设计就难以解决这样的问题,我们可以为它添加一个见证人来解决此事。
假设你一天要干100件事情,会让你非常忙碌而且极易犯错,这个时候如果为你设计了多层架构,多层的人员为你服务,你就可以很轻松的达成这100件事并且每一件事情可以做的很细致,不会那么容易犯错。
所以,如何设计使得程序运作时和编码时更易于控制就是设计模式要解决的问题。
我常用的设计模式:
1、整个项目的管理类似公司的管理,有不同的部门不同的负责人,有部门上下级关系,有人员上下级关系。
2、每个人员尽可能小范围的打交道,如果是自己私有的功能仅封装到自己内部。
3、不要越级管理,不要越管理者操作。
4、同级别的人员或部门相互协调完成一件事的时候可以设立专门的监管者来负责此事情。
5、层级依赖,中层依赖底层的实现,高层依赖中层的实现。
6、降低耦合性,多利用接口和抽象类,分工开发。
7、整体处理可以参考树形结构,一个类仅与同级或上下级打交道。
-- 例如当你要和它打交道但是权限不够的话可以通过你的上级,当你和它打交道它处于更底层时,应该分派人员去做这件事。
我认为管理项目就像是管理公司,合理的管理和规划可以引导至一个良好的路线上,
同时也像是开启了上帝模式,你可以操纵一切,你是你,你也不是你,你是这个程序,你也是程序中的每一个成员。
至于协同开发管理一个大型软件,就像你是这个世界的管理员,而别人是别的世界管理员,你们之间需要打交道。
关于23种设计模式
这些都是单位设计模式,一个软件中会运用到里面的多种组合而成的,视情况使用,根据需求和要解决的问题,衡量后使用,对于它的使用只是为了更好地解决问题,当你开发了足够多的项目时,每次必然会有些总结,可能在事后明白如果当初这么设计可以更好的解决问题,不会很容易出现那么多BUG,或者在重构的时候使用更好的方式来解决同样的问题,这绝不是一朝一夕能够学成的,所以初学程序的人员可以不必要纠结这些更不需要背诵这些东西,因为它会在日后无形中存在于你的设计中,时不时的再看看,对照自己的设计,弥补缺陷或完善设计。
当你足够多的编码的时候,你可以先放一放编码,在设计一个东西前,尽可能的花费更多的时间在架构图上面,或者编写一些接口或抽象类来不断的磨合这个设计,让他更加完美更加易于控制、维护、扩展。
23种设计模式示例:以下以 Flash AS3代码示例:
简单工厂模式:利用接口来引用以及操作实际创建的实例,而实际创建出来的实例可以用一个方法或多个方法来创建
package { import flash.display.Sprite; public class Main extends Sprite { /** * 构造函数 * */ public function Main() { // 创建一个MailSender实例,它同时也是Sender类型 var m:Sender = createSender("mail"); m.send(); // 创建一个SmsSender实例,它同时也是sms类型 var s:Sender = createSender("sms"); s.send(); } /** * 普通模式:利用字符串创建实例 * 创建一个Sender,具体会创建哪个类的实例取决于参数type * @param type 类别 * @return 接口Sender的实现类 * */ public function createSender(type:String):Sender{ switch(type){ case "mail": return new MailSender(); case "sms": return new SmsSender(); } return null; } /** * 多方法模式:利用多个方法创建实例,避免传递的字符串出错导致为null * @return * */ public function createMailSender():Sender{ return new MailSender(); } public function createSmsSender():Sender{ return new SmsSender(); } /** * 多静态方法模式:利用多个静态方法创建实例,避免传递的字符串出错导致为null * @return * */ public static function createMailSender():Sender{ return new MailSender(); } public static function createSmsSender():Sender{ return new SmsSender(); } } }
package { public interface Sender { /** * 发送 * */ function send():void; } }
package { public class MailSender implements Sender { public function MailSender() { } /** * Mail方式发送 * */ public function send():void { trace("MailSender"); } } }
package { public class SmsSender implements Sender { public function SmsSender() { } /** * Sms方式发送 * */ public function send():void { trace("SmsSender"); } } }
工厂方法模式:利用工厂接口来引用和操作和具体的工厂,然后利用产品接口引用和操作这个工厂产生的具体的产品实例
package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var p:Provider = new SendMailFactory(); var s:Sender = p.produce(); s.send(); } } }
package { public interface Provider { function produce():Sender; } }
package { public class SendMailFactory implements Provider { public function SendMailFactory() { } public function produce():Sender { return new MailSender(); } } }
package { public class SendSmsFactory implements Provider { public function SendSmsFactory() { } public function produce():Sender { return new SendSmsFactory(); } } }
package { public interface Sender { function send():void; } }
package { public class MailSender implements Sender { public function MailSender() { } public function send():void { trace("MailSender"); } } }
package { public class SmsSender implements Sender { public function SmsSender() { } public function send():void { trace("SmsSender"); } } }
抽象工厂模式:接口工厂操作具体的工厂,工厂生产多个具体的产品,不同的工厂生产的同种产品也有相同的接口,如XX工厂牌肥皂和YY工程牌肥皂,肥皂是接口,XX工厂牌肥皂和YY工厂牌肥皂是具体的实现类
package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var f1:Factory = new darkFactory(); var keyboard:Keyboard = f1.createKeyboard(); keyboard.keyDown(0); var mouse:Mouse = f1.createMouse(); mouse.mouseUp(0); var f2:Factory = new kdsFactory(); var keyboard2:Keyboard = f2.createKeyboard(); keyboard2.keyDown(0); var mouse2:Mouse = f2.createMouse(); mouse2.mouseUp(0); } } }
package { public interface Factory { function createKeyboard():Keyboard; function createMouse():Mouse; } }
package { public interface Keyboard { function keyDown(key:uint):void; } }
package { public interface Mouse { function mouseUp(key:uint):void; } }
package { public class darkFactory implements Factory { public function darkFactory() { } public function createKeyboard():Keyboard{ return new darkKeyboard(); } public function createMouse():Mouse{ return new darkMouse(); } } }
package { public class kdsFactory implements Factory { public function kdsFactory() { } public function createKeyboard():Keyboard{ return new kdsKeyboard(); } public function createMouse():Mouse{ return new kdsMouse(); } } }
package { public class darkKeyboard implements Keyboard { public function darkKeyboard() { } public function keyDown(key:uint):void { trace("darkKeyboard!!!"); } } }
package { public class darkMouse implements Mouse { public function darkMouse() { } public function mouseUp(key:uint):void { trace("darkMouse!!!"); } } }
package { public class kdsMouse implements Mouse { public function kdsMouse() { } public function mouseUp(key:uint):void { trace("kdsMouse..."); } } }
package { public class kdsKeyboard implements Keyboard { public function kdsKeyboard() { } public function keyDown(key:uint):void { trace("kdsKeyboard..."); } } }
单例模式:保证整个内存里只存在一份该类的实例
package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var m:Mouse = Mouse.getMouse(); var m2:Mouse = Mouse.getMouse(); trace(m==m2); // true } } }
package { public class Mouse { public static var self:Mouse; public function Mouse() { } public static function getMouse():Mouse{ return self?self:self=new Mouse(); } } }
建造者模式:流程顺序用接口控制,保证流程是相同的,具体不同的施工实现该流程不同,生产出来的产品细节上就不一样
package { import Interface.Builder; import Interface.product; import flash.display.Sprite; public class Main extends Sprite { public function Main() { var builder1:Builder = new darkBuilder(); var director:Director = new Director(builder1); director.construct(); var product1:product = builder1.getResult(); trace(product1.name); var builder2:Builder = new kdsBuilder(); var director2:Director = new Director(builder2); director2.construct(); var product2:product = builder2.getResult(); trace(product2.name); } } }
package Interface { public interface Builder { function buildPartA():void; function buildPartB():void; function buildPartC():void; function getResult():product; } }
package Interface { public interface product { function get name():String; } }
package { import Interface.Builder; import Interface.product; public class darkBuilder implements Builder { private var darkStr:String = ""; public function darkBuilder() { } public function buildPartA():void { darkStr+="AAA"; } public function buildPartB():void { darkStr+="BBB"; } public function buildPartC():void { darkStr+="CCC"; } public function getResult():product { return new kdsProduct(darkStr); } } }
package { import Interface.product; public class darkProduct implements product { private var _name:String; public function darkProduct(name:String) { _name = name + "[is Dark]"; } public function get name():String { return _name; } } }
package { import Interface.Builder; public class Director { private var _builder:Builder; public function Director(builder:Builder) { _builder = builder; } public function construct():void{ _builder.buildPartA(); _builder.buildPartB(); _builder.buildPartC(); } } }
package { import Interface.Builder; import Interface.product; public class kdsBuilder implements Builder { private var str:String=""; public function kdsBuilder() { } public function buildPartA():void { str+="kdsA "; } public function buildPartB():void { str+="kdsB "; } public function buildPartC():void { str+="kdsC "; } public function getResult():product { return new kdsProduct(str); } } }
package { import Interface.product; public class kdsProduct implements product { private var _name:String; public function kdsProduct(name:String) { _name = name; } public function get name():String { return _name; } } }
原型模式:利用接口或抽象类,要有一个clone的方法,方便克隆这个实例
package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var p:Product = new kdsProduct("yes"); var pClone:Object = p.clone(); trace(p,pClone,p==pClone,p.name,pClone.name); } } }
package { import flash.utils.ByteArray; public class kdsProduct extends Product { public function kdsProduct(name:String) { this.name = name; } public override function clone():Object{ var by:ByteArray = new ByteArray(); by.writeObject(this); by.position = 0; var obj:Object = by.readObject(); return obj; } } }
package { public class Product { public var name:String; public function Product() { } public function clone():Object { return null; } } }
类的适配器模式:父类有接口中的A方法,子类有接口中的B方法,子类接上该接口,父类不接
package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var p:IPeople = new Son(); p.func1(); p.func2(); } } }
package { public interface IPeople { function func1():void; function func2():void; } }
package { public class Father { public function Father() { } public function func1():void{ trace("this is function 1!!"); } } }
package { public class Son extends Father implements IPeople { public function Son() { super(); } public function func2():void { trace("this is function 2!"); } } }
对象的适配器模式:某个实例中存在另外一个实例,调用这个实例中的某方法时实际上是用另一个实例执行了该方法,而这某个实例接入与某接口
package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var f:Father = new Father(); var s:IPeople = new Son(f); s.func1(); s.func2(); } } }
package { public interface IPeople { function func1():void; function func2():void; } }
package { public class Father { public function Father() { } public function func1():void{ trace("this is function 1!!"); } } }
package { public class Son implements IPeople { private var father:Father; public function Son(father:Father) { this.father = father; super(); } public function func2():void { trace("this is function 2!"); } public function func1():void { father.func1(); } } }
接口的适配器模式:主要是接口方法太多但我只用到少数几个,这个时候要有一个父类来空实现该接口,子类继承于父类,重写关键的方法即可
package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var p:IPeople = new Son(); p.func1(); p.func2(); } } }
package { public interface IPeople { function func1():void; function func2():void; function func3():void; function func4():void; function func5():void; } }
package { public class Father implements IPeople { public function Father() { } public function func1():void{ } public function func2():void{ } public function func3():void{ } public function func4():void{ } public function func5():void{ } } }
package { public class Son extends Father { public function Son() { } public override function func2():void { trace("this is function 2!"); } public override function func1():void{ trace("this is function 1!"); } } }
装饰模式:未包装的类和包装的类都接入于同一个接口,但包装的实例中含有未包装的实例对象,所以调用同一方法可以在未包装的基础上再包装一些东西
package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var np:NormalPeople = new NormalPeople(); var ap:AdvancePeople = new AdvancePeople(np); ap.say(); } } }
package Interface { public interface IPeople { function say():void; } }
package { import Interface.IPeople; public class NormalPeople implements IPeople { public function NormalPeople() { } public function say():void{ trace("I am a normal people!"); } } }
package { import Interface.IPeople; public class AdvancePeople implements IPeople { private var norPeople:NormalPeople; public function AdvancePeople(norPeople:NormalPeople) { this.norPeople = norPeople; } public function say():void { trace("My name is kds"); norPeople.say(); trace("And I like games!"); } } }
代理模式:有些类似装饰模式但你不用控制被包装和包装者,只要创建一个代理者,它会自动创建相关人员来进行工作
package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var pr:Proxy = new Proxy(); pr.say(); } } }
package Interface { public interface IPeople { function say():void; } }
package { import Interface.IPeople; public class NormalPeople implements IPeople { public function NormalPeople() { } public function say():void{ trace("I am a normal people!"); } } }
package { import Interface.IPeople; public class Proxy implements IPeople { private var norPeople:NormalPeople; public function Proxy() { this.norPeople = new NormalPeople(); } public function say():void { trace("My name is kds"); norPeople.say(); trace("And I like games!"); } } }
外观模式:一个产品包含不同的组件,实现产品的某个功能的时候实际上是调用不同组件的功能组合而成,对于此类设计方式,个人觉得编程语言应该提供便捷的方式申明该类仅供哪个或哪几个类调用,不会被其他的外部访问
package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var p:People = new People(); p.dance(); } } }
package { public class People { private var foot:Foot; private var face:Face; private var hand:Hand; public function People() { foot = new Foot(); face = new Face(); hand = new Hand(); } public function dance():void{ trace("开始跳舞了!"); foot.dance(); face.dance(); hand.dance(); trace("跳舞结束"); } } }
package { public class Face { public function Face() { } public function dance():void{ trace("保持微笑!"); } } }
package { public class Foot { public function Foot() { } public function dance():void{ trace("脚步舞动!"); } } }
package { public class Hand { public function Hand() { } public function dance():void{ trace("比划有节奏!"); } } }
组合模式:树形结构很适用,比如容器和子容器的关系
package { import flash.display.Sprite; import kds.Sprite; public class Main extends flash.display.Sprite { public function Main() { var sp:kds.Sprite = new kds.Sprite("father"); var spSon1:kds.Sprite = new kds.Sprite("son1"); var spSon2:kds.Sprite = new kds.Sprite("son2"); var spGrandson:kds.Sprite = new kds.Sprite("grandson1"); sp.addChild(spSon1); sp.addChild(spSon2); spSon1.addChild(spGrandson); trace(sp.name,sp.numChildren); // father 2 trace(sp.getChildAt(0).name,sp.getChildAt(0).numChildren); // son1 1 trace(sp.getChildAt(1).name,sp.getChildAt(1).numChildren); // son2 0 trace(spGrandson.parent==sp.getChildAt(0)); // true } } }
package kds { public class Sprite { private var _name:String; private var _parent:Sprite; private var _childs:Vector.<Sprite> = new Vector.<Sprite>(); public function Sprite(name:String) { _name=name; } public function get name():String{ return _name; } public function setParent(sp:Sprite):void{ _parent = sp; } public function get parent():Sprite{ return _parent; } public function addChild(sp:Sprite):void{ _childs.push(sp); sp.setParent(this); } public function removeChild(sp:Sprite):void{ _childs.splice(_childs.indexOf(sp),1); sp.setParent(null); } public function get numChildren():uint{ return _childs.length; } public function getChildAt(index:int):Sprite{ return _childs[index]; } } }
享元模式:就是打造一个对象池,不用的对象扔回来,不过为了下次复用的时候不会夹杂着上次使用它时的设置,你可以在扔回来的时候clear或者重设它数据的时候覆盖全部属性
package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var obj1:Object = objPool.getObject(); var obj2:Object = objPool.getObject(); var obj3:Object = objPool.getObject(); objPool.disposeObject(obj1); objPool.disposeObject(obj2); var obj4:Object = objPool.getObject(); var obj5:Object = objPool.getObject(); trace(obj4==obj1,obj5==obj2); // true true } } }
package { public class objPool { private static var objs:Array = []; public static function getObject():Object{ if(objs.length==0){ var obj:Object = new Object(); return obj; } return objs.shift(); } public static function disposeObject(obj:Object):void{ // clear 如果每次用的obj的key不一样就删除掉全部,如果都是统一的后面使用时候覆盖了就没事不用做清理 for (var key:String in obj){ delete obj[key]; } objs.push(obj); } } }
策略模式:实现提供多个方法给用户来决定选择使用哪一个,更新的话只需要更新新的方法即可
package { import Interface.ISplit; import flash.display.Sprite; public class Main extends Sprite { public function Main() { var split:ISplit = new SplitMinus(); trace(split.split("1+1-3=5")); // 1+1,3=5 } } }
package Interface { public interface ISplit { function split(str:String):Array; } }
package { import Interface.ISplit; public class SplitMinus implements ISplit { public function SplitMinus() { } public function split(str:String):Array { return str.split("-"); } } }
package { import Interface.ISplit; public class SplitPlus implements ISplit { public function SplitPlus() { } public function split(str:String):Array{ return str.split("+"); } } }
模板方法模式:打造一个抽象类,可以放置抽象方法或实现方法,子类继承后重写抽象方法或实现方法
package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var c:CalcSon = new CalcSon(); trace(c.plus(3,3)); trace(c.minus(3,3)); } } }
package { public class Calc { public function Calc() { } public function plus(a:int,b:int):int{ return 0; } public function minus(a:int,b:int):int{ return a-b; } } }
package { public class CalcSon extends Calc { public function CalcSon() { } public override function plus(a:int, b:int):int{ return a+b; } } }
观察者模式:一个管理员管理着多个观察者,当某个状态被改变的时候要通知给所有观察者,这样每个观察者才能是观察到最新的信息
package { import Interface.IPeople; import flash.display.Sprite; public class Main extends Sprite { public function Main() { var peo1:IPeople = new People(); var peo2:IPeople = new People(); PeopleManager.reg(peo1); PeopleManager.reg(peo2); PeopleManager.sendMessage("hello!"); } } }
package Interface { public interface IPeople { function receiveMessage(msg:String):void; } }
package { import Interface.IPeople; public class PeopleManager { private static var peoples:Vector.<IPeople> = new Vector.<IPeople>(); public static function reg(peo:IPeople):void{ peoples.push(peo); } public static function sendMessage(str:String):void{ for each (var peo:IPeople in peoples){ peo.receiveMessage(str); } } } }
package { import Interface.IPeople; public class People implements IPeople { private var id:int=idCount++; private static var idCount:int; public function People() { } public function receiveMessage(msg:String):void { trace(id,msg); } } }
迭代子模式:一个产品内部的集合利用另外一个迭代器来遍历查询操作
package { import Interface.IItems; import Interface.IIterator; import flash.display.Sprite; public class Main extends Sprite { public function Main() { var items:IItems = new Items(); var it:IIterator = items.iterator; while(it.haseNext) trace("next",it.next()); var obj:Object while(obj=it.previous()) trace("last",obj); } } }
package Interface { public interface IItems { function get iterator():IIterator; function getObject(i:int):Object; function get size():int; } }
package Interface { public interface IIterator { function previous():Object; function next():Object; function get haseNext():Boolean; function first():Object; } }
package { import Interface.IItems; import Interface.IIterator; public class Items implements IItems { public var datas:Array = [1,2,3,4,5,6,7]; public function Items() { } public function get iterator():IIterator { return new Iterator(this); } public function getObject(i:int):Object { return datas[i]; } public function get size():int { return datas.length; } } }
package { import Interface.IIterator; public class Iterator implements IIterator { private var items:Items; private var index:int = -1; public function Iterator(items:Items) { this.items = items; } public function previous():Object { return index==-1?null:index==0?items.getObject(--index):items.getObject(--index); } public function next():Object { return index==items.size-1?items.getObject(index):items.getObject(++index); } public function get haseNext():Boolean { return index==items.size-1?false:true; } public function first():Object { return items.getObject(0); } } }
责任链模式:创建一个链表,比如你可以让它自动推进
package { import Interface.IList; import flash.display.Sprite; public class Main extends Sprite { public function Main() { var firstList:IList = new List("No.First"); var nowList:IList = firstList; for(var i:int = 0;i<Math.random()*10+5;i++){ var list:IList = new List("No."+int(Math.random()*10000).toString()); nowList.setNext(list); nowList = list; } firstList.say(); } } }
package Interface { public interface IList { function say():void; function setNext(next:IList):void; } }
package { import Interface.IList; public class List implements IList { private var next:IList; private var name:String; public function List(name:String) { this.name = name; } public function setNext(next:IList):void{ this.next = next; } public function say():void{ trace(name); if(next)next.say(); } } }
命令模式:发出命令,让别人执行,或者执行完毕后通知我,可以不用关注别人怎么去做的,只要求得到结果
package { import Interface.ICommander; import Interface.IMan; import flash.display.Sprite; public class Main extends Sprite { public function Main() { // 我让指挥官命令跑步,指挥官只是命令其下面的人跑步,至于具体怎么跑,每个人不一样 var commander:ICommander = new Commander(); var cook:IMan = new Cook(); var soldier:IMan = new Soldier(); commander.addMan(cook); commander.addMan(soldier); commander.commandRun(); commander.commandWalk(); } } }
package Interface { public interface ICommander { function commandRun():void; function commandWalk():void; function addMan(man:IMan):void; } }
package Interface { public interface IMan { function run():void; function walk():void; } }
package { import Interface.ICommander; import Interface.IMan; public class Commander implements ICommander { private var mans:Vector.<IMan> = new Vector.<IMan>(); private var soldier:Array = []; public function Commander() { } public function commandRun():void { mans.forEach(function(prt:IMan,i:int,arr:Vector.<IMan>):void{ prt.run(); },this); } public function commandWalk():void { mans.forEach(function(prt:IMan,i:int,arr:Vector.<IMan>):void{ prt.walk(); },this); } public function addMan(man:IMan):void{ mans.push(man); } } }
package { import Interface.IMan; public class Cook implements IMan { public function Cook() { } public function run():void { trace("我是厨子,跑不动,只能跑500米!"); } public function walk():void { trace("我是厨子,我可以走2000米!"); } } }
package { import Interface.IMan; public class Soldier implements IMan { public function Soldier() { } public function run():void { trace("我是士兵,但我受伤了,我只能跑50米!"); } public function walk():void { trace("我是士兵,跟你说过我受伤了,不过走的话可以走500米!"); } } }
备忘录模式:利用第三方记录某个人当前的状态,这样如果有需要可以还原它当时的状态。
package { import Interface.ICommander; import Interface.IMan; import flash.display.Sprite; public class Main extends Sprite { public function Main() { // 我让指挥官命令跑步,指挥官只是命令其下面的人跑步,至于具体怎么跑,每个人不一样 var commander:ICommander = new Commander(); var cook:IMan = new Cook(); var soldier:IMan = new Soldier(); commander.addMan(cook); commander.addMan(soldier); commander.commandRun(); commander.commandWalk(); } } }
package Interface { public interface ICommander { function commandRun():void; function commandWalk():void; function addMan(man:IMan):void; } }
package Interface { public interface IMan { function run():void; function walk():void; } }
package { import Interface.ICommander; import Interface.IMan; public class Commander implements ICommander { private var mans:Vector.<IMan> = new Vector.<IMan>(); private var soldier:Array = []; public function Commander() { } public function commandRun():void { mans.forEach(function(prt:IMan,i:int,arr:Vector.<IMan>):void{ prt.run(); },this); } public function commandWalk():void { mans.forEach(function(prt:IMan,i:int,arr:Vector.<IMan>):void{ prt.walk(); },this); } public function addMan(man:IMan):void{ mans.push(man); } } }
package { import Interface.IMan; public class Cook implements IMan { public function Cook() { } public function run():void { trace("我是厨子,跑不动,只能跑500米!"); } public function walk():void { trace("我是厨子,我可以走2000米!"); } } }
package { import Interface.IMan; public class Soldier implements IMan { public function Soldier() { } public function run():void { trace("我是士兵,但我受伤了,我只能跑50米!"); } public function walk():void { trace("我是士兵,跟你说过我受伤了,不过走的话可以走500米!"); } } }
状态模式:根据这个人的状态改变,它自己所执行的相同的方法结果可能就不一样,同时你也可以根据它的状态做出不同的事
package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var p:People = new People(); p.run(); p.state = State.HURT; p.run(); } } }
package { public class People { public var state:uint = State.NORMAL; public function People() { } public function run():void{ switch(state) { case State.NORMAL: trace("正常的跑步"); break; case State.HURT: trace("装作正常的跑步"); break; } } } }
package { public class State { public static const NORMAL:uint = 0; public static const HURT:uint = 1; } }
访问者模式:调用我的方法实际上是让另一个访问者来访问我的公开属性,如果需求有更改只要替换访问者即可
package { import Interface.Ivisitor; import flash.display.Sprite; public class Main extends Sprite { public function Main() { // 东西 var goods:Goods = new Goods(); // 建立两个不同级别的访问者,前者访问级别低 var v:Ivisitor = new Visitor(); goods.showName(v); var v2:Ivisitor = new VisitorAdvance(); goods.showName(v2); } } }
package { import Interface.Ivisitor; public class Goods { public var name:String = "好东西"; public var sexsurname:String = "我不是" public function Goods() { } public function showName(visitor:Ivisitor):void{ return visitor.showName(this); } } }
package { import Interface.Ivisitor; public class Visitor implements Ivisitor { public function Visitor() { } public function showName(goods:Goods):void{ trace(goods.name); } } }
package { import Interface.Ivisitor; public class VisitorAdvance implements Ivisitor { public function VisitorAdvance() { } public function showName(goods:Goods):void{ trace(goods.sexsurname + goods.name); } } }
package Interface { public interface Ivisitor { function showName(goods:Goods):void; } }
中介者模式:我并不直接操作people进行工作,而是通过中介者-Shop,让中介者来对people操作
package { import Interface.IShop; import flash.display.Sprite; public class Main extends Sprite { public function Main() { var shop:IShop = new Shop(); shop.createShopKeeper(); shop.workAll(); } } }
package Interface { public interface IShop { function createShopKeeper():void; function workAll():void; } }
package { public class People { private var workTime:int; public function People() { workTime = int(Math.random()*6)+2; } public function work():void{ trace("我工作",workTime,"小时"); } } }
package { import Interface.IShop; public class Shop implements IShop { private var peopleArr:Array = []; public function Shop() { } public function createShopKeeper():void { peopleArr.push(new People()); peopleArr.push(new People()); peopleArr.push(new People()); peopleArr.push(new People()); } public function workAll():void { for each(var people:People in peopleArr){ people.work(); } } } }
解释器模式:根据这个人的状态改变,它自己所执行的相同的方法结果可能就不一样,同时你也可以根据它的状态做出不同的事
package { import Interface.IMachining; import flash.display.Sprite; public class Main extends Sprite { public function Main() { var item:Item = new Item("盾牌"); var fire:IMachining = new FireMachining(); var ice:IMachining = new IceMachining(); fire.packing(item); trace(item.name); ice.packing(item); trace(item.name); } } }
package Interface { public interface IMachining { function packing(item:Item):void; } }
package { public class Item { public var name:String; public function Item(name:String) { this.name = name; } } }
package { import Interface.IMachining; public class IceMachining implements IMachining { public function IceMachining() { } public function packing(item:Item):void { item.name = "冰霜的" + item.name; } } }
package { import Interface.IMachining; public class FireMachining implements IMachining { public function FireMachining() { } public function packing(item:Item):void { item.name = "火焰的" + item.name; } } }