您的位置:首页 > 编程语言 > C语言/C++

阿里巴巴2016校园招聘在线笔试(C/C++)附加题 第二题

2015-08-24 13:08 441 查看
题目描述:

假设目前有3个程序A, B和C,需要相互传输数据,我们需要给做一个中转程序P。

A 读写的数据是经过某压缩格式azip压缩过的。

B 读写的数据需要base64编码。

C 读写数据需要压缩格式bzip压缩后base64编码。

现在假设已有工具函数 :

std::string azip(const std::string& input);
std::string aunzip(const std::string& input);
std::string base64encode(const std::string& input);
std::string base64decode(const std::string& input);
bool bzip(const std::string& input, std::string* output);
bool bunzip(const std::string& input, std::string* output);


请给中转程序P设计格式转换的工具类。注意设计的通用性,比如:可能有新的角色加入,要求给做加密解密等。

参考思路:笔试期间,直接设计了6个函数来实现3个程序之间的相互转换。按照这种方式,如果现在加入新的角色D进来,那么要再设计6个函数。假设现在有n个程序,已经用f(n) = n*(n-1)个函数实现了它们之间的相互转换,f(n) - f(n-1) = n*(n-1) - (n-1)*(n-2) = 2n-2, 也就是增加一个程序就要再设计2n-2这么多个函数。另外如果修改了一个程序的读写方式,那么就需要修改2n-2个函数。所以这种设计方式可扩展性和维护性不好。

通过思考,可以发现用多态的方式来解决这个问题,对每个程序设计出它的加解密函数,只需要设计一个转换函数,需要转换的两个程序设计作为参数,具体代码如下:

std::string azip(const std::string& input){return "";}
std::string aunzip(const std::string& input){return "";}
std::string base64encode(const std::string& input){return "";}
std::string base64decode(const std::string& input){return "";}
bool bzip(const std::string& input, std::string* output){return true;}
bool bunzip(const std::string& input, std::string* output){return true;}

class task {
public:
virtual void in(const string& input) {
}
virtual string out() {
return "";
}
protected:
string str;
};

class taskA: public task {
public:
void in(const string& input) {
str = azip(input);
}
string out() {
return aunzip(str);
}
};

class taskB: public task {
public:
void in(const string& input) {
str = base64encode(input);
}
string out() {
return base64decode(str);
}
};

class taskC: public task {
public:
void in(const string& input) {
bzip(input, &str);
str = base64encode(str);
}
string out() {
string temp = base64decode(str);
bunzip(temp, &str);
return str;
}
};

void tansition(task& left, task& right) {
right.in(left.out());
}

int main() {
task* t1 = new taskA;
task* t2 = new taskB;
tast* t3 = new taskC;

t1->in("abc");
transition(*t1, *t2);
transition(*t2, *t3);

return 0;
}


如果现在添加一个角色D,那么只需要添加一个类taskD,包括两个成员函数in和out,即每添加一个角色,只需要添加一个类(两个函数)。如果修改了一个角色的读写方式,也只需要修改该类的两个函数,其它地方不变。所以该设计方法相对上面的那个具有更好的扩展性和维护性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: