cocos2d For MVP
cocos2d的强大,这里就不多说了。主要是在开发时,各种代码耦合,不便于维护。所以今天就来个MVP模式,在cocos2d上的实现。
关于MVP模式,就不多解释了,直接上码。
Model 部分
#import <Foundation/Foundation.h> @protocol IPlayer <NSObject> - (void)move; @end #import "cocos2d.h" #import "IPlayer.h" @interface Player : CCSprite<IPlayer> @end #import "Player.h" @implementation Player - (id)init { if (self = [super init]) { } return self; } - (void)move { CCMoveTo *move = [CCMoveTo actionWithDuration:3.0f position:ccp(240,160)]; [self runAction:move]; } @end
Presenter 部分
#import <Foundation/Foundation.h> #import "IStartView.h" #import "IPlayer.h" @protocol IStartPresenter <NSObject> - (void)playerMove; @end #import <Foundation/Foundation.h> #import "IStartPresenter.h" @interface StartPresenter : NSObject<IStartPresenter> { } @property (nonatomic,assign) id<IStartView> view; @property (nonatomic,assign) id<IPlayer> player; - (id)initWithView:(id<IStartView>) view Entity:(id<IPlayer>) model; - (void)playerMove; @end #import "StartPresenter.h" @implementation StartPresenter @synthesize view = view_; @synthesize player = player_; - (id)initWithView:(id<IStartView>) view Entity:(id<IPlayer>) model { if (self = [super init]) { view_ = view; player_ = model; } return self; } - (void)playerMove { [player_ move]; } @end
最后 View 的部分
#import <Foundation/Foundation.h> @protocol IStartView <NSObject> @end #import "cocos2d.h" #import "IStartView.h" #import "IStartPresenter.h" @interface StartView : CCLayer<IStartView> { } @property (nonatomic,assign) id<IStartPresenter> presenter; +(CCScene *) scene; @end #import "StartView.h" #import "StartPresenter.h" #import "Player.h" @implementation StartView @synthesize presenter = presenter_; +(CCScene *) scene { // 'scene' is an autorelease object. CCScene *scene = [CCScene node]; // 'layer' is an autorelease object. StartView *layer = [StartView node]; // add layer as a child to scene [scene addChild: layer]; // return the scene return scene; } - (id)init { if (self = [super init]) { Player *player = [[Player alloc] initWithFile:@"Icon-72.png"]; player.position = ccp(0, 0); self.presenter = [[StartPresenter alloc] initWithView:self Entity:player]; [self addChild:player]; CCLabelTTF *label = [CCLabelTTF labelWithString:@"Move" fontName:@"Marker Felt" fontSize:64]; CCMenuItemLabel *item = [CCMenuItemLabel itemWithLabel:label target:self selector:@selector(move)]; CCMenu *menu = [CCMenu menuWithItems:item, nil]; [self addChild:menu]; } return self; } - (void)move { [presenter_ playerMove]; } @end
这样就完成了。运行,点击模拟器屏幕上大大的Move菜单,方块Icon就动起来了。MVP模式让UI和逻辑分开了,但是开发的时候要定义一大坨的接口。
总之没有完美的东西,只有合适的东西,根据需要去取舍。
有空的话再讲讲cocos2d for MVC,这个更抽象,更难理解。