标签:适配器 模式 void 单例 设计模式 LcdDevice ct
1、策略设计模式
策略模式:依赖c++的多态,抽象类的指针可以访问所有子类对象,(纯虚函数),可以用一个指针访问所有策略的实现类
#include <iostream>
using namespace std;
/*策略设计模式*/
class Strategy
{
public:
Strategy(){}
virtual ~Strategy(){}
virtual void strategy()=0;
};
//实现策略A
class ContoneStrategyA: public Strategy
{
public:
virtual void strategy()
{
cout<<"strategy A"<<endl;
}
};
//实现策略B
class ContoneStrategyB: public Strategy
{
public:
virtual void strategy()
{
cout<<"strategy B"<<endl;
}
};
class Context
{
Strategy *sty;
public:
Context(Strategy* s){this->sty = s;}
~Context()
{
delete sty;
}
void doWork()
{
sty->strategy();
}
};
int main()
{
Context *ct ;
ct = new Context(new ContoneStrategyA());
ct->doWork();
delete ct;
ct = new Context(new ContoneStrategyB());
ct->doWork();
return 0;
}
2、单例设计模式
单例模式:单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例单例模式(不能让一个程序打开两次 );单例模式也称为单件模式、单子模式。有很多地方需要这样的功能模块,如系统的日志输出等。
#include <iostream>
using namespace std;
/*单例设计模式*/
class LcdDevice
{
LcdDevice(){}
LcdDevice(LcdDevice& lcd){}
public:
~LcdDevice(){}
static LcdDevice* getInstance();//静态成员函数
protected:
static LcdDevice * instance;//定义静态成员变量--LcdDevice指针
};
LcdDevice* LcdDevice::instance = nullptr;//在数据段分配8个字节,并且初始化为nullptr
LcdDevice* LcdDevice::getInstance()
{
if(instance == nullptr)
{
instance = new LcdDevice();//创建一个lcd对象
}
return instance;
}
void fun()
{
LcdDevice* lcd = LcdDevice::getInstance();
}
int main()
{
LcdDevice* lcd = LcdDevice::getInstance();
return 0;
}
3、适配器设计模式
适配器模式:把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口原因不匹配而无法一起工作的两个类能够一起工作。
现有电源220v
需要的电源5v
把220v转5v---这个过程称为适配
#include <iostream>
using namespace std;
class chargeHigh{
public:
virtual void outHigh(){
cout<<"out high"<<endl;
}
};
class chargeLow{
public:
virtual void outLow()=0;
};
class Adapter:public chargeHigh, public chargeLow
{
public:
virtual void outLow()
{
this->high_to_low();
cout<<"out low"<<endl;
}
void high_to_low()
{
this->outHigh();
cout<<"high to low"<<endl;
}
};
int main()
{
chargeLow *low = new Adapter();
low->outLow();
return 0;
}
标签:适配器,模式,void,单例,设计模式,LcdDevice,ct 来源: https://blog.csdn.net/qq_40602000/article/details/95981976
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。