Any encryption algorithm should have methods encrypt and decrypt. This can be represented as an interface called Cipher. It is then possible
to provide different implementations of the encryption algorithm that work in different ways. For example, you might write a CaeserCipher
that replaces a with d, b with e, c with f, etc., or you might write a ReverseCipher that replaces a with z and b with y, etc. You could
then write software that sends encrypted messages and that is capable of working with any Cipher.
Write an interface Cipher and provide at least two implementations of your choice. Write a single function void testCipher(Cipher& toTest)
that can test any Cipher works correctly.
这个实现起来思路也是比较简单的,代码量比前两个稍微大了一些,写了Cipher用于实现相应的接口:对比视图(0ffb34a558d47180b8f246c3e4b96bec491d3b27...c6174630b7c06f03d9e9f6dd0c47cf18ebc92548) · 云金杞/learn_cpp_series - Gitee.com
Cipher.h
#pragma once #include "testing.h" class Cipher { public: /* A virtual destructor */ virtual ~Cipher() {}; /* This method is abstract, there is no definition */ virtual std::string encrypt(const std::string &x) = 0; virtual std::string decrypt(const std::string &x) = 0; }; class CaeserCipher :public Cipher { public: CaeserCipher(); std::string encrypt(const std::string& x); std::string decrypt(const std::string& x); }; class ReverseCipher :public Cipher { public: ReverseCipher(); std::string encrypt(const std::string& x); std::string decrypt(const std::string& x); }; void testCipher();
Cipher.cpp
#include "Cipher.h" CaeserCipher::CaeserCipher() {}; std::string CaeserCipher::encrypt(const std::string& x) { std::string result = x; for (size_t i = 0; i < x.size(); i++) { result[i] = x[i] + 3; } return result; }; std::string CaeserCipher::decrypt(const std::string& x) { std::string result = x; for (size_t i = 0; i < x.size(); i++) { result[i] = x[i] - 3; } return result; }; ReverseCipher::ReverseCipher() {}; std::string ReverseCipher::encrypt(const std::string& x) { std::string result = x; for (size_t i = 0; i < x.size(); i++) { result[i] = 'z' - (x[i] - 97); } return result; }; std::string ReverseCipher::decrypt(const std::string& x) { std::string result = x; for (size_t i = 0; i < x.size(); i++) { result[i] = 'z' - (x[i] - 97); } return result; }; //------------------------------------------ // tests for Cipher //------------------------------------------ static void testCaeserCipher() { CaeserCipher cip; std::string s = "abc"; std::string result = cip.encrypt(s); ASSERT("def" == result); std::string result2 = cip.decrypt(result); ASSERT(s == result2); } static void testReverseCipher() { ReverseCipher rci; std::string s = "abczyx"; std::string result = rci.encrypt(s); std::cout << "result = " << result << std::endl; ASSERT("zyxabc" == result); std::string result2 = rci.decrypt(result); std::cout << "result2 = " << result2 << std::endl; ASSERT(s == result2); } void testCipher() { TEST(testCaeserCipher); TEST(testReverseCipher); }