Chapter 22 bridge mode

A synthetic / polymeric use doctrine

  • Synthesis / polymerization using the principle to make use of synthetic / polymeric, try not to use class inheritance.
  • Represents the polymerization has a weak relationship between the object A is reflected objects may contain B, but the object is not a part B A of the object; the synthesis has a strong relationship, and reflects part of the overall strict relationship, parts and Like the whole life cycle.
  • Synthesis of the object using the priority / polymerization will help you keep each class is encapsulated, and concentrated on a single task. Such classes and class hierarchies will remain small-scale, and less likely to grow to uncontrollable monster.
  • Inheritance is a strong coupling structure becomes the parent class, subclass must be changed.
  • When we use inheritance, we must consider the relationship is used when the "is-a" the.

Two concepts

  • Bridge mode, an abstraction of its separation so that they can be varied independently.

Three UML diagrams

Four C ++ code to achieve

#include "pch.h"
#include <iostream>
using namespace std;
//手机软件 Imolementor
class HandsetSoft
{
public:
    virtual void Run() = 0;
};
//手机游戏 ConcreteImplementorA
class HandsetGame : public HandsetSoft
{
public:
    void Run() override
    {
        cout << "运行手机游戏" << endl;
    }
private:
};
//通讯录 ConcreteImplementorB
class HandsetAddressList : public HandsetSoft
{
public:
    void Run() override
    {
        cout << "运行手机通信录" << endl;
    }
};

//手机品牌 Abstraction
class HandsetBrand
{
public:
    void SetHandsetSoft(HandsetSoft* soft)
    {
        this->soft = soft;
    }
    virtual void Run() = 0;
protected:
    HandsetSoft* soft;
};

//品牌N品牌M具体类 RefinedAbstraction
class HandsetBrandN : public HandsetBrand
{
public:
    void Run() override
    {
        this->soft->Run();
    }
};
class HandsetBrandM : public HandsetBrand
{
public:
    void Run() override
    {
        this->soft->Run();
    }
};
//客户端调用代码
int main()
{
    HandsetBrand* ab;
    ab = new HandsetBrandN();

    ab->SetHandsetSoft(new HandsetGame());
    ab->Run();

    ab->SetHandsetSoft(new HandsetAddressList());
    ab->Run();

    ab = new HandsetBrandM();
    ab->SetHandsetSoft(new HandsetGame());
    ab->Run();

    ab->SetHandsetSoft(new HandsetAddressList());
    ab->Run();

    system("pause");
    return 0;
}

Guess you like

Origin www.cnblogs.com/Manual-Linux/p/11140864.html