c++ 设计模式(一) 代理模式

1 显示效果


2 代码

#include "Windows.h"
#include "iostream"
using namespace std;

class PayInterface //定义支付接口基类
{
public:
	PayInterface() //该类虽然不能被实例化,但是它的子类实例化时,也会调用它的构造函数
	{
		cout << "支付接口构造函数!" << endl;
	}
	virtual void pay() = 0; //纯虚函数
};

class Pay : public PayInterface //支付类
{

public:
	static Pay * PayPoint;
	Pay()
	{
		PayPoint = this;  //子类的指针赋值给父类
		cout << "支付类的构造函数" << endl;
	}
	~Pay()
	{
		cout << "支付类的析构函数" << endl;
	}
	static Pay * GetInstancePoint() //静态成员函数
	{
		if(PayPoint != NULL)
		return PayPoint;
	}
	virtual void pay() =0; //纯虚函数
};
 Pay * Pay::PayPoint = NULL;
class WeiXinPay : public Pay//微信支付类
{
public:
	WeiXinPay()
	{
		cout << "微信支付类构造函数" << endl;
	}
	~WeiXinPay()
	{
		cout << "微信支付类析构函数" << endl;
	}
	virtual void pay()
	{
		cout <<"调用微信支付接口"<< endl;
    }
};

class AliPay : public Pay//支付宝支付类
{
public:
	AliPay()
	{
		cout << "调用支付宝支付类的构造函数" << endl;
	}
	~AliPay()
	{
		cout << "调用支付宝支付类的析构函数" << endl;
	}
	void pay()//override父类纯虚函数
	{
		cout << "调用支付宝接口" << endl;
	}
};
void main()
{
	//Pay pay;  该语句是错误的:因为Pay类中有纯虚函数,因此不能实例化
	WeiXinPay WxPay;
	Pay::GetInstancePoint()->pay(); //多态 调用微信的支付接口
	cout << "-------------" << endl;
	AliPay APay;
	Pay::GetInstancePoint()->pay();//多态 调用
	system("pause");
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值