? ? 将抽象部分与它的实现部分分离,使它们都可以独立地变化。
? ? 抽象(Abstraction)、细化抽象(Refined Abstraction)、抽象实现者(Implementor)、具体实现者(Concrete Implementor)
? ? 3.1?分离接口及其实现部分
? ? 3.2?提高可扩充性
? ? 3.3?实现细节对客户透明
? ? N/A
? ? 5.1?抽象工厂可以用来创建和配置一个特定的Bridge模式。
? ? 5.2 适配器模式用来帮助无关的类协同工作,通常在系统完成后(类已经设计好)才使用,
? ? ? ? ? ?而桥接模式在系统开始时(设计类之前)就被使用。
#pragma once
#include <iostream>
using namespace std;
class Implementor
{
public:
virtual void OperationImp() = 0;//基本操作
};
class ConcreteImplementorA : public Implementor
{
public:
virtual void OperationImp()
{
cout << "ConcreteImplementorA:OperationImp" << endl;
}
};
class ConcreteImplementorB : public Implementor
{
public:
virtual void OperationImp()
{
cout << "ConcreteImplementorB:OperationImp" << endl;
}
};
class ImplementorFactory
{
private:
static ImplementorFactory* s_singleton;
private:
ImplementorFactory(){}
public:
static ImplementorFactory* Instance()
{
if (s_singleton == 0)
{
s_singleton = new ImplementorFactory;
}
return s_singleton;
}
public:
Implementor* MakeImplementor(int type)
{
if (1 == type)
{
return new ConcreteImplementorA;
}
else
{
return new ConcreteImplementorB;
}
}
};
class Abstraction
{
protected:
Implementor* m_pImplementor;
int m_type;
public:
Abstraction()
{
m_pImplementor = 0;
m_type = 0;
}
~Abstraction()
{
delete m_pImplementor;
}
virtual void Operation()
{
//Operation可以由多个基本操作组合
//例如可以多次调用OperationImp
GetImplementor()->OperationImp();
GetImplementor()->OperationImp();
}
protected:
Implementor* GetImplementor()
{ //从单例工厂里获取Implementor
return ImplementorFactory::Instance()->MakeImplementor(m_type);
}
};
class RefinedAbstraction1 : public Abstraction
{
public:
RefinedAbstraction1()
{
m_type = 1;
}
};
class RefinedAbstraction2 : public Abstraction
{
public:
RefinedAbstraction2()
{
m_type = 2;
}
};
Bridge.cpp:
#include "Bridge.h"
ImplementorFactory* ImplementorFactory::s_singleton = 0;
#include "Bridge.h"
int main()
{
Abstraction* pAbstraction = new RefinedAbstraction1;
pAbstraction->Operation();
delete pAbstraction;
pAbstraction = new RefinedAbstraction2;
pAbstraction->Operation();
delete pAbstraction;
return 0;
}
运行结果:
6.1 接口Abstraction和实现Implementor分离,接口类维护一个实现类的指针(3.1)
6.2 可以单独对Abstraction或Implementor扩充(生成新的子类)(3.2)
6.3 使用了单例的工厂来生成Implementor
?