桥接模式:使用组合的方式将抽象化(Abstraction)与实现化(Implementation)分离,使得二者可以独立地变化。
这样的好处是抽象和实现可以分别独立地变化,系统的耦合性也得到了很好的降低.
Bridge.h
#ifndef _BRIDGE_H_
#define _BRIDGE_H_
class TimeImp
{
public:
TimeImp(int hr, int min);
virtual ~TimeImp() {}
void virtual tell();
protected:
int hr_, min_;
};
class CivilianTimeImp: public TimeImp
{
public:
CivilianTimeImp(int hr, int min, int pm);
void tell();
protected:
char pm_[8];
};
class ZoneTimeImp: public TimeImp
{
public:
ZoneTimeImp(int hr, int min, int zone);
void tell();
protected:
char zone_[32];
};
class Time
{
public:
Time();
virtual ~Time();
Time(int hr, int min);
void tell();
protected:
TimeImp * imp_;
};
class CivilianTime: public Time
{
public:
CivilianTime(int hr, int min, int pm);
};
class ZoneTime: public Time
{
public:
ZoneTime(int hr, int min, int zone);
};
#endif
Bridge.cpp
#include <iostream>
#include "Bridge.h"
#include "string.h"
using std::cout;
using std::endl;
TimeImp::TimeImp(int hr, int min)
{
hr_ = hr;
min_ = min;
}
void TimeImp::tell()
{
cout << "current time is " << hr_ << ":" << min_ << endl;
}
CivilianTimeImp::CivilianTimeImp(int hr, int min, int pm):TimeImp(hr, min)
{
if (pm > 12)
strcpy(pm_, "PM");
else
strcpy(pm_, "AM");
}
void CivilianTimeImp::tell()
{
cout << "current civilian time is " << hr_ << ":" << min_ << ":" << pm_ << endl;
}
ZoneTimeImp::ZoneTimeImp(int hr, int min, int zone):TimeImp(hr, min)
{
if (6 == zone)
strcpy(zone_, "Sinkiang");
else
strcpy(zone_, "Beijing");
}
void ZoneTimeImp::tell()
{
cout << "current zone time is " << hr_ << ":" << min_ << ":" << zone_ << endl;
}
Time::Time()
{
}
Time::~Time()
{
if (NULL != imp_)
{
delete imp_;
imp_ = NULL;
}
}
Time::Time(int hr, int min)
{
imp_ = new TimeImp(hr, min);
}
void Time::tell()
{
imp_->tell();
}
CivilianTime::CivilianTime(int hr, int min, int pm)
{
imp_ = new CivilianTimeImp(hr, min, pm);
}
ZoneTime::ZoneTime(int hr, int min, int zone)
{
imp_ = new ZoneTimeImp(hr, min, zone);
}
main.cpp
#include "Bridge.h"
int main()
{
Time *tm[3];
tm[0] = new Time(11, 22);
tm[1] = new CivilianTime(10, 20, 20);
tm[2] = new ZoneTime(9, 30, 6);
for (int i = 0; i < 3; ++i)
{
tm[i]->tell();
delete tm[i];
}
return 0;
}
Makefile
cc=g++
exe=main
obj= main.o Bridge.o
$(exe): $(obj)
$(cc) -o $(exe) $(obj)
main.o: Bridge.h
$(cc) -c main.cpp
Prototype.o: Bridge.h
$(cc) -c Bridge.cpp
clean:
rm -rf *o $(exe)
output:
current time is 11:22
current civilian time is 10:20:PM
current zone time is 9:30:Sinkiang
本文深入探讨了桥接模式的概念、原理及其实现过程,通过具体的代码实例展示了如何使用组合方式将抽象化与实现化分离,从而实现系统模块化的高效设计。文中详细介绍了Time类及其子类的实现,包括CivilianTime和ZoneTime,展示了如何通过桥接模式降低系统的耦合性,提升代码的灵活性和可维护性。

4万+

被折叠的 条评论
为什么被折叠?



