大话设计模式代理模式c++实现

代理模式

其他二十三种设计模式

#include<iostream>

using namespace std;
//代理模式
//被追求者类
class Girl {
    
    
public:
	void Name(string _name) {
    
    
		this->name = _name;
	}
	string GetName() {
    
        //void类型时会导致没有与"<<"匹配的运算符
		return name;      //不能直接cout<<name,需要return一个返回值
	}

private:
	string name;
};

//代理接口类
class IGiveGift {
    
    
public:
	virtual void GiveDolls() = 0;
	virtual void GiveFlowers() = 0;
	virtual void GiveChocolate() = 0;
};

//追求者类
class Pursuit :public IGiveGift {
    
    
public:
	Pursuit(Girl* name) {
    
    
		this->mm = name;
	}
	virtual void GiveDolls() {
    
    
		cout << mm->GetName() << " 送你洋娃娃!" << endl;  //cout << &(this->mm)时和 &(mm->GetName())不是同一个地址
	}
	virtual void GiveFlowers() {
    
    
		cout << mm->GetName() << " 送你花!" << endl;
	}
	virtual void GiveChocolate() {
    
    
		cout << mm->GetName() << " 送你巧克力!" << endl;
	}

private:
	Girl* mm;
};

//代理类
class Proxy :public IGiveGift {
    
    
public:
	Proxy(Girl* name) {
    
    
		this->gg = new Pursuit(name);
	}
	virtual void GiveDolls() {
    
    
		this->gg->GiveDolls();
	}
	virtual void GiveFlowers() {
    
    
		this->gg->GiveFlowers();
	}
	virtual void GiveChocolate() {
    
    
		this->gg->GiveChocolate();
	}
	
private:
	Pursuit* gg;
};

void test1() {
    
    
	Girl* jiaojiao = new Girl();
	jiaojiao->Name("李娇娇");

	Proxy* daili = new Proxy(jiaojiao);

	daili->GiveDolls();
	daili->GiveFlowers();
	daili->GiveChocolate();

	delete daili;
	delete jiaojiao;
}

int main() {
    
    

	test1();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wode_0828/article/details/114162922
今日推荐