1 #include <iostream> 2 #include <string> 3 #include <map> //用户名,用户的下载 4 using namespace std; 5 6 class DownloadManager; 7 class DownState { 8 public: 9 virtual void Down(string User, string DownItem, DownloadManager* p) = 0; 10 protected: 11 DownState(){} 12 }; 13 14 class NormalDownState :public DownState{ 15 public: 16 void Down(string User, string DownItem, DownloadManager* p) { 17 cout << "欢迎您下载本资源" << endl; 18 } 19 }; 20 class RepeateDownState :public DownState { 21 public: 22 void Down(string User, string DownItem, DownloadManager* p) { 23 cout << "请不要重复下载" << endl; 24 } 25 }; 26 27 class SpiteDownState :public DownState { 28 public: 29 void Down(string User, string DownItem, DownloadManager* p) { 30 cout << "你有恶意下载的嫌疑,即将取消下载资格" << endl; 31 } 32 }; 33 34 class BlackDownState :public DownState { 35 public: 36 void Down(string User, string DownItem, DownloadManager* p) { 37 cout << "您的下载过于频繁,被列入黑名单,禁止登录本系统" << endl; 38 } 39 }; 40 41 class DownloadManager { 42 public: 43 map<string, string> getMapDown() { 44 return m_mapDown; 45 } 46 void Down(string User, string DownItem) { 47 int oldDownCount = 0; 48 if (m_mapDownCount.count(User) > 0) { 49 oldDownCount = m_mapDownCount[User]; 50 } 51 else { 52 m_mapDownCount[User] = 0; 53 } 54 oldDownCount++; 55 m_mapDownCount[User] = oldDownCount; 56 if (oldDownCount == 1) { 57 m_pState = new NormalDownState(); 58 } 59 else if (oldDownCount > 1 && oldDownCount < 3) { 60 m_pState = new RepeateDownState(); 61 } 62 else if (oldDownCount >= 3 && oldDownCount < 5) { 63 m_pState = new SpiteDownState(); 64 } 65 else if (oldDownCount >= 5) { 66 m_pState = new BlackDownState(); 67 } 68 m_pState->Down(User, DownItem, this); 69 } 70 private: 71 DownState* m_pState;//持有状态处理对象 72 map<string, string> m_mapDown; 73 map<string, int> m_mapDownCount; 74 }; 75 76 int main(void) { 77 DownloadManager* pVM = new DownloadManager; 78 for (int i = 0;i < 5;i++) { 79 pVM->Down("dst", "设计模式完全手册C++语言描述"); 80 } 81 system("pause"); 82 return 0; 83 }