代理模式.cpp
# include <iostream>
# include <memory>
# include <vector>
# include <string>
# include <fstream>
using namespace std;
namespace ns1
{ class WebAddr { public : virtual ~ WebAddr ( ) { } virtual void visit ( ) = 0 ; } ; class WebAddr_Shopping : public WebAddr { public : void visit ( ) override { cout << "visit WebAddr_Shopping!" << endl; } } ; class WebAddr_Video : public WebAddr { public : void visit ( ) override { cout << "visit WebAddr_Video!" << endl; } } ; class WebAddrProxy : public WebAddr { shared_ptr< WebAddr> mp_webaddr; public : WebAddrProxy ( const shared_ptr< WebAddr> & pwebaddr) : mp_webaddr ( pwebaddr) { } public : void visit ( ) override { if ( mp_webaddr != nullptr ) mp_webaddr-> visit ( ) ; } } ; class WebAddr_Shopping_Proxy : public WebAddr { public : void visit ( ) override { shared_ptr< WebAddr> p_webaddr ( new WebAddr_Shopping ( ) ) ; p_webaddr-> visit ( ) ; } } ;
} namespace ns2
{ static vector< string> g_fileItemList; class ReadInfo { public : virtual ~ ReadInfo ( ) { } virtual void read ( ) = 0 ; } ; class ReadInfoFromFile : public ReadInfo { public : void read ( ) override { ifstream fin ( ".vscode/settings.json" ) ; if ( ! fin) { cout << "failure" << endl; return ; } g_fileItemList. clear ( ) ; string linebuf; while ( getline ( fin, linebuf) ) { if ( ! linebuf. empty ( ) ) g_fileItemList. push_back ( linebuf) ; } fin. close ( ) ; } } ; class ReadInfoProxy : public ReadInfo { bool m_loaded = false ; public : void read ( ) override { if ( ! m_loaded) { m_loaded = true ; shared_ptr< ReadInfo> rf ( new ReadInfoFromFile ( ) ) ; rf-> read ( ) ; cout << "read from file: " << endl; } else { cout << "read from cache: " << endl; } for ( auto iter = g_fileItemList. cbegin ( ) ; iter != g_fileItemList. cend ( ) ; ++ iter) cout << * iter << endl; } } ;
} int main ( )
{
# if 0 using namespace ns1; shared_ptr< WebAddr> wba1 ( new WebAddr_Shopping ( ) ) ; wba1-> visit ( ) ; shared_ptr< WebAddr> wba2 ( new WebAddr_Video ( ) ) ; wba2-> visit ( ) ;
# endif # if 0 using namespace ns1; shared_ptr< WebAddr> wba1 ( new WebAddr_Shopping ( ) ) ; shared_ptr< WebAddr> wbaproxy1 ( new WebAddrProxy ( wba1) ) ; wbaproxy1-> visit ( ) ; shared_ptr< WebAddr> wba2 ( new WebAddr_Video ( ) ) ; shared_ptr< WebAddr> wbaproxy2 ( new WebAddrProxy ( wba2) ) ; wbaproxy2-> visit ( ) ;
# endif # if 0 using namespace ns1; shared_ptr< WebAddr> wbasproxy ( new WebAddr_Shopping_Proxy ( ) ) ; wbasproxy-> visit ( ) ;
# endif # if 1 using namespace ns2; shared_ptr< ReadInfo> preadinfoproxy ( new ReadInfoProxy ( ) ) ; preadinfoproxy-> read ( ) ; preadinfoproxy-> read ( ) ; preadinfoproxy-> read ( ) ;
# endif return 0 ;
}