Use code and UML diagrams to resolve the design pattern of the bridge pattern in depth analysis

  • 2020-04-02 01:04:21
  • OfStack

The bridging pattern is the separation of independence and implementation.
Different manufacturers make different products... The product and the manufacturer have this combination relationship.

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013053115502618.gif ">

In the code


//Bridge.cpp: defines the entry point for the console application.
   
#include "stdafx.h"
#include <iostream>
using namespace std;
class Product
{
public:
 Product(){}
 virtual ~Product(){}

 virtual void make()=0;
 virtual void sell()=0;
};
class ProductA:public Product
{
public:
 ProductA(){}
 virtual ~ProductA(){}
 virtual void make()
 {
  cout<<"ProductA:make()"<<endl;
 }
 virtual void sell()
 {
  cout<<"ProductA:sell()"<<endl;
 }
};
class ProductB:public Product
{
public:
 ProductB(){}
 virtual ~ProductB(){}
 virtual void make()
 {
  cout<<"ProductB:make()"<<endl;
 }
 virtual void sell()
 {
  cout<<"ProductB:sell()"<<endl;
 }
};
class Corp
{
public:
 Corp(Product* pro)
  :m_product(pro)
 {}
 virtual ~Corp()
 {
  delete m_product;
 }

 virtual void process()
 {
  m_product->make();
  m_product->sell();
 }
private:
 Product *m_product;
};
class CorpA:public Corp
{
public:
 CorpA(Product * pro) :Corp(pro){}
 virtual ~CorpA(){}
 virtual void process()
 {
  cout<<"CorpA():process()"<<endl;
  Corp::process();
 }
};
class CorpB:public Corp
{
public:
 CorpB(Product * pro) :Corp(pro){}
 virtual ~CorpB(){}
 virtual void process()
 {
  cout<<"CorpB:process()"<<endl;
  Corp::process();
 }
};
int _tmain(int argc, _TCHAR* argv[])
{
 Product* product;
 product = new ProductA;
 Corp * corp ;
 corp = new CorpA(product);
 corp ->process();
 cout<<"----------"<<endl;
 product= new ProductB;
 corp = new CorpB(product);
 corp->process();
 return 0;
}

Production and manufacturers are independent implementation, fully give freedom...
Ok, that's it for today... Continue to learn


Related articles: