_008_外观模式_适配器模式

=======================================


一 外观模式


1 外观模式概念

外观模式就相当于封装,把类似功能的类,都定义在另外一个类里


2 外观模式代码

#include <iostream>
using namespace std;

class SYS1
{
public:
	void test()
	{
		cout << "SYS1" << endl;
	}
};

class SYS2
{
public:
	void test()
	{
		cout << "SYS2" << endl;
	}
};


class SYS3
{
public:
	void test()
	{
		cout << "SYS3" << endl;
	}
};


class SYS4
{
public:
	void test()
	{
		cout << "SYS4" << endl;
	}
};

//外观模式就相当于封装,把类似的功能,都定义在另外一个类里
class Face
{
public:
	void one_two()
	{
		sys1.test();
		sys2.test();
    }

	void three_two()
	{
		sys3.test();
		sys2.test();
	}

private:
	SYS1 sys1;
	SYS1 sys2;
	SYS1 sys3;
	SYS1 sys4;
};

int main()
{
	Face *f = new Face;
	f->one_two();
	f->three_two();
}

二 适配器模式


1 适配器模式概念

类似于转接口,比如手机充电器,家庭电压是220V,但是手机充电

不能超过5V,所以用手机充电器充电,手机充电器就是适配器


2 适配器模式代码

#include <iostream>
using namespace std;

//5v电压的类
//class V5
//{
//public:
//	void useV5() {
//		cout << "使用了5v的电压" << endl;
//	}
//};

//充电需要5V电压
class V5
{
public:
	virtual void useV5() = 0;
};

//目前只有v220的类 没有v5
class V220
{
public:
	void useV220() {
		cout << "使用了220v的电压" << endl;
	}
};

//定义一个中间的适配器类
class Adapter :public V5
{
public:
	Adapter(V220 * v220)
	{
		this->v220 = v220;
	}
	~Adapter()
	{
		if (this->v220 != NULL)
		{
			delete this->v220;
		}
	}

	virtual void useV5() {
		v220->useV220(); //调用需要另外的方法
	}

private:
	V220 *v220;
};

//手机只能用5V充电,这个类不能更改
class iPhone
{
public:
	iPhone(V5 *v5) :v5(v5){}

	//充电的方法
	void charge()
	{
		cout << "iphone手机进行了充电" << endl;

		//因为V5是抽象类,我们传入的适配器是他的子类,所以会调用适配器的useV5方法
		v5->useV5();
	}

	~iPhone()
	{
		if (this->v5 != NULL) {
			delete this->v5;
		}
	}

private:
	V5*v5;
};

int main()
{
	iPhone *phone = new iPhone(new Adapter(new V220));
	phone->charge();

}

适配器模式需要注意的是,需要修改一次需转换的类,比如上面的5V

本来是一个类,需要修改成一个抽象类,才能使用适配器













猜你喜欢

转载自blog.csdn.net/yzj17025693/article/details/80593989