C++ 代理模式(Proxy Pattern)
阿新 • • 發佈:2019-02-12
隨意寫的,主要用作程式碼練習,防止程式碼生疏,敬請見諒!
本意是能夠寫成一個多用途的代理模式,結果還是寫廢了,其他方面來說,沒有時間重整它,有的寫法是沒有太大意義的。期望有點價值吧
首先放一個代理模式的講解,個人覺得寫得不錯,如果你是尋求代理模式的用法用途的話,值得一看:
//ProxyPattern.h
//ProxyPattern.cpp#pragma once #include <iostream> #include <typeinfo> #include <string> template<typename ReturnValue,typename T,typename T2> class IMutiUser { public: virtual ReturnValue (T)(...)= 0; virtual ReturnValue GetReturnType()const = 0; }; template<typename ReturnValue, typename T,typename T2> class IMutiProxy :public IMutiUser<ReturnValue,T,T2> { protected: T2* mMImpl; public: virtual ReturnValue (T)(...) override; virtual ReturnValue GetReturnType()const override; }; template<typename ReturnValue, typename T,typename T2> ReturnValue IMutiProxy<ReturnValue,T,T2>::T(...) { mMImpl = new T2(); if (mMImpl != nullptr) { std::cout << "Show Something of IMutiProxy!" << std::endl; mMImpl->T(); } ReturnValue temp= NULL; return temp; } template<typename ReturnValue, typename T,typename T2> ReturnValue IMutiProxy<ReturnValue, T,T2>::GetReturnType()const { ReturnValue temp=NULL; return temp; } template<typename ReturnValue, typename T,typename T2> class IMutiImplement :public IMutiUser<ReturnValue,T,T2> { public: virtual ReturnValue(T)(...) override; virtual ReturnValue GetReturnType() const override; }; template<typename ReturnValue, typename T,typename T2> ReturnValue IMutiImplement<ReturnValue, T,T2>::T(...) { std::cout << "show something!" << std::endl; std::cout << "You could dispose something for custom function ." << std::endl; ReturnValue temp=NULL; return temp; } template<typename ReturnValue, typename T,typename T2> ReturnValue IMutiImplement<ReturnValue, T,T2>::GetReturnType() const { ReturnValue temp=NULL; return temp; }
#include "ProxyPattern.h" int show(int number) { std::cout << "Current Number is :" + number << std::endl; return 1; } int main(...) { int(*func)(int b); func = show; IMutiUser<int, decltype(func),IMutiImplement<int,decltype(func),void>>* temp = new IMutiProxy<int, decltype(func),IMutiImplement<int, decltype(func),void>>(); temp->T(); temp->GetReturnType(); system("pause"); return 0; }