合成/聚合复用原则:尽量使用合成/聚合,尽量不要使用类继承
聚合:表示弱拥有关系,体现的是A对象可以包含B对象,但B对象不是A对象的一部分。
合成:强拥有关系,体现严格的部分和整体的关系,部分和整体的声明周期一样。
实例:
大雁-----------<>雁群
<>
|
|
翅膀
游戏,通讯录功能都是软件,让其分离与手机的耦合。
应该增加一个手机品牌抽象类和手机软件抽象类
手机品牌包含手机软件,但软件不是品牌的一部分,因此是聚合关系。
优点:优先使用对象的合成/聚合将有助于你保持每个类被封装,并被集中在单个任务上。这样累和类继承层次会保持较小规模,并且不太可能增长为不可控制的庞然大物。
原因:继承是一种强耦合的结构,父类变,子类就必须改变。
桥接模式:将抽象部分与它的实现部分分离,使他们都可以独立地变化。
实现指的是:抽象类和它的派生类用来实现自己的对象。
本质:实现方式有很多种,把实现独立出来,让它们各自地变化。
本质:
实现系统可能有多角度分类,每一种分类都有可能变化,就把这种多角度分离出让它们独立变化,减少它们之间的耦合。
main.cpp
#include <iostream>
#include <stdlib.h>
#include <memory>
#include "PhoneSoft.h"
#include "PhoneBrand.h"
using namespace std;
void process()
{
std::shared_ptr<PhoneBrand> ptrApple(new Apple());
std::shared_ptr<PhoneBrand> ptrNokia(new Nokia());
std::shared_ptr<PhoneSoft> ptrGame(new PhoneGame());
std::shared_ptr<PhoneSoft> ptrAddressList(new PhoneAddressList());
ptrApple->setPhoneSoft(ptrGame);
ptrApple->run();
ptrApple->setPhoneSoft(ptrAddressList);
ptrApple->run();
}
int main(int argc,char* argv[])
{
process();
system("pause");
return 0;
}
PhoneBrand.h
#ifndef PHONEBRAND_H
#define PHONEBRAND_H
#include <memory>
#include "PhoneSoft.h"
class PhoneBrand
{
public:
PhoneBrand();
virtual ~PhoneBrand(void);
virtual void run() = 0;
void setPhoneSoft(std::shared_ptr<PhoneSoft> ptrPhoneSoft);
protected:
std::shared_ptr<PhoneSoft> _ptrPhoneSoft;
};
class Apple : public PhoneBrand
{
public:
void run();
};
class Nokia : public PhoneBrand
{
public:
void run();
};
#endif
PhoneBrand.cpp
#include "PhoneBrand.h"
PhoneBrand::PhoneBrand()
{
}
PhoneBrand::~PhoneBrand(void)
{
}
void PhoneBrand::setPhoneSoft(std::shared_ptr<PhoneSoft> ptrPhoneSoft)
{
_ptrPhoneSoft = ptrPhoneSoft;
}
void Apple::run()
{
_ptrPhoneSoft->run();
}
void Nokia::run()
{
_ptrPhoneSoft->run();
}
PhoneSoft.h
#ifndef PHONESOFT_H
#define PHONESOFT_H
class PhoneSoft
{
public:
PhoneSoft(void);
virtual ~PhoneSoft(void);
virtual void run();
};
class PhoneGame : public PhoneSoft
{
public:
void run();
};
class PhoneAddressList : public PhoneSoft
{
public:
void run();
};
#endif
PhoneSoft.cpp
#include "PhoneSoft.h"
#include <iostream>
using namespace std;
PhoneSoft::PhoneSoft(void)
{
}
PhoneSoft::~PhoneSoft(void)
{
}
void PhoneSoft::run()
{
}
void PhoneGame::run()
{
cout << "运行手机游戏" << endl;
}
void PhoneAddressList::run()
{
cout << "运行手机通讯录" << endl;
}