Details of C++ design mode Proxy (agent mode)

  • 2020-06-07 04:56:32
  • OfStack

Agency model is easy to understand, is to do a certain thing on behalf of others, for example, we need to buy fruit, 1 usually go to the supermarket or fruit store to buy fruit, few people go to the orchard to buy fruit, orchard is the production of fruit, but rarely sell fruit, here, fruit store, the supermarket becomes the agent.

First define an abstract class that provides all the function interfaces.

1. Define the abstract class that sells the fruit, the interface, which the orchard and the supermarket inherit from.


#pragma once
class CSellFruits// define 1 An abstract class 
{
public:
 CSellFruits(void);
 virtual ~CSellFruits(void);
 virtual void sellapple()=0; // Define the interface, sell the apple 
 virtual void sellorange()=0;// Define the interface, sell the orange 
};
 
#include "SellFruits.h"
CSellFruits::CSellFruits(void)
{
}
 
 
CSellFruits::~CSellFruits(void)
{
}

2. Define the specific class, namely the orchard class. The orchard produces fruit, but generally does not buy fruit


#pragma once
#include "sellfruits.h"
#include <stdio.h>
class COrchard :
 public CSellFruits
{
public:
 COrchard(void);
 virtual ~COrchard(void);
 virtual void sellapple();
 virtual void sellorange();
};
 
#include "Orchard.h"
COrchard::COrchard(void)
{
}
 
 
COrchard::~COrchard(void)
{
}
 
void COrchard::sellapple()
{
 printf("Sell apple\n");
}
 
void COrchard::sellorange()
{
 printf("Sell orange\n");
}

3. Define the proxy class, the proxy class that sells fruit


#pragma once
#include "sellfruits.h"
#include "Orchard.h"
#include <stdio.h>
class CProcySellFruits :
 public CSellFruits
{
public:
 CProcySellFruits(void);
 virtual ~CProcySellFruits(void);
 virtual void sellapple();
 virtual void sellorange();
private:
 CSellFruits *p_SellFruits; // Pass in the interface object 
};
 
#include "ProcySellFruits.h"
CProcySellFruits::CProcySellFruits(void):p_SellFruits(NULL)
{
}
 
 
CProcySellFruits::~CProcySellFruits(void)
{
}
 
void CProcySellFruits::sellapple()
{
 if(this->p_SellFruits==NULL)
 {
 this->p_SellFruits=new COrchard(); // Instantiate with the class being represented 
 }
 this->p_SellFruits->sellapple();// Agent orchard sells apples 
}
 
void CProcySellFruits::sellorange()
{
 if(this->p_SellFruits==NULL)
 {
 this->p_SellFruits=new COrchard(); // Instantiate with the class being represented 
 }
 this->p_SellFruits->sellorange();// Agent orchard sells oranges 
}

4. Actual invocation


CProxySellFruits* p=new CProxySellFruits(); // Sell fruit in the agent category 
 p->SellApple();
 p->SellOrange();

Related articles: