结构型设计模式---桥接模式(Bridge)

来源:互联网 发布:郑州市儿童编程教育 编辑:程序博客网 时间:2024/06/05 03:13

桥接模式:使用组合的方式将抽象化(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 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

0 0
原创粉丝点击