好久没写博客了,今晚突发想写写什么,最近也没有什么事情可用作,空暇时间多了,人就懒了
最近喜欢看王爽老师的汇编语言和我所理解的cocos2dx还有一些C++的设计模式。
接下来是及格常见的设计模式:
1.关于单例:
class singleton
{
public:
static singleton* getinstance();
protected:
singleton();
static singleton* _singleton;
}
singleton* singleton::_singleton=NULL;
singleton::singleton()
{
}
singleton* singleton::getinstance()
{
if(_singleton==NULL)
{
_singleton=new singleton();
}
return _singleton;
}
单例的好处就是在整个程序里面,不管多少次实例化,对象只有一个;
2.工厂模式:
看了很多书和cocos2d的代码,发现很多都是使用了工厂模式,低耦合,高内聚是我们写函数的目标,工厂模式提供了两个最重要的功能:
1 将要实现的功能封装在factory里面;
2 延迟了实例化;
就好比我们去KFC 买快餐,我们点了可乐和鸡翅,我们只需要在窗口前指出我们需要可乐和鸡翅,而不需要去理解怎么去做可乐和鸡翅,不用自己去准备原材料。
代码如下
#include "iostream"
using namespace std;
class product;
class factory
{
public:
factory(){};
~factory(){};
product* concreteProduct();
};
product* factory::concreteProduct()
{
cout<<"create product"<<endl;
return new initProduct();
}
class product
{
public:
product(){};
~product(){};
virtual product* nameProduct()=0;
};
class initProduct : public product
{
public:
initProduct();
~initProduct();
virtual product* nameProduct();
};
void main()
{
factory* fac=new factory();
initProduct* _pr=fac->concreteProduct();
}
关于回调函数:
其实我们在写很多函数的时候都要涉及要回调函数 代码如下:
#include "iostream"
using namespace std;
typedef void (__stdcall Callfunc)(int a,int b,bool test=true);
void main()
{
sum(Callfunc callfunc);
}
void sum(Callfunc callfunc)
{
callfunc(2,3);
}
void callfunc(int a,int b,bool test)
{
if(test)
{
return a+b;}
return 0;
}
话说好久没写这么多了....