组合模式

今天在看cocos2d的时候,看到Action的设计采用了组合模式装饰模式,可以将一系列的action组合起来,让CCNodec对象执行,就像给CCNode下达一系列的命令一样.

例如以下代码:

1 CCActionInterval* move =CCMoveBy::actionWithDuration(0.5f, ccp(0,160)); 
2 CCActionInterval*rotate = CCRotateBy::actionWithDuration(2, 360); 
3 CCActionInterval*scale = CCScaleBy::actionWithDuration(2, 5); 
4 CCActionInterval*opacity = CCFadeOut::actionWithDuration(2); 
5 CCActionInterval*fadein = CCFadeIn::actionWithDuration(2); 
6 CCActionInterval* scaleback =CCScaleTo::actionWithDuration(1, 1); 
7 CCFiniteTimeAction*seq0 = CCSequence::actions(move, rotate, scale, opacity, fadein, scaleback,NULL);
8 Actor->runAction(seq0); 

于是就看了一下组合模式,写了个小例子:

 1 #include <vector> 
 2 //组合模式是为了让访问单一对象与多个对象具有一致性。 
 3 // 想一下我们就可以知道可以用循环去遍历对象数组。提供通用接口
 4 abstract class Component 
 5 { 
 6 public: vector<Component> vect ; 
 7 virtual int add() = 0 ; 
 8 virtual int del(&Component) = 0 ;
 9  virtual int run() = 0 ; 
10 }; 
11 class composite:public Component 
12 { 
13 public: composite();
14  int add(&Component);
15  int del(&Component);
16  int run(); 
17 ~composite(); 
18 }; 
19 
20 composite::composite() { } 
21 composite::add(Component &item)
22  { vect.push_back(item); }
23  composite::del(Component &item) 
24 { 
25          for( vector<Component*>::iterator it=vect.begin();it!=vect.end() )
26          {  
27           //erase()并不会删除*it指向的对象,所以我们需要额外释放它 
28           //这里如何判断两个对象是否相等呢?我们可以判断它们的地址是否相等
29                it == item ? vect.erase(it) : it++ ; 
30            }
31             //使用swap来减少容量 
32            vector(vect).swap(vect); 
33 } 
34 composite::run() 
35 { 
36       vector<Component*>::iterator it ; 
37       for( it= vect.begin();it!=vect.end();it++ ) 
38           { *it->run() ; }
39 }
40  composite::~composite() {} 
41 int main() 
42 { 
43        composite vect = new composite(); 
44        //单个对象 
45         Component single = new Component(); 
46         vect.add(&single); 
47         vect.run(); 
48         Component mul1 = new Component(); 
49         Component mul2 = new Component(); 
50         Component mul3 = new Component(); 
51         vect.add(&mul1); 
52         vect.add(&mul2); 
53         vect.add(&mul3); 
54         vect.run(); 
55         //向量内存放的只是对象的副本,所以析构时不会释放对象的内存,我们需要手动释放 
56         delete single ; 
57         delete mul1; 
58         delete mul2; 
59         delete mul3; 
60          return 0; 
61 }

平时用C++不多,看了大半天的STL,真感慨C++的内存管理如此复杂...

原文地址:https://www.cnblogs.com/trying/p/2863838.html