实现:
1) cImage:抽象类;
cImageReal:派生类, 不可直接实例化;
cImageProxy:派生代理类, 可直接实例化用来代理cImageReal;
NOTICE:派生代理类用来简化对特定派生类的使用.
使用:
实例化代理类, 然后使用.
1) 设计框架
/*image.hpp*/
#pragma once
#ifndef __IMAGE__HPP
#define __IMAGE__HPP
#include <string>namespace __proxy{class cImage{
public:virtual ~cImage();
protected: cImage();
public:virtual void display() = 0;
};}
#include "image_real_proxy.hpp"#endif/*image_real_proxy.hpp*/
#pragma once
#ifndef __IMAGE_REAL_PROXY_HPP
#define __IMAGE_REAL_PROXY_HPP
#include "image.hpp"
#include <string>namespace __proxy{class cImageReal:virtual public cImage{
public:cImageReal(std::string const &filename);
public:void display() override;
private:void loadFromDisk(std::string const &filename);std::string _M_filename;
};}namespace __proxy{class cImageProxy:virtual public cImage{
public:cImageProxy(std::string const &filename);
public:void display() override;
private:cImageReal *_M_image = nullptr;std::string _M_filename;
};}
#endif
2) 实现框架
/*image.cpp*/
#include "image.hpp"
#include <stdio.h>namespace __proxy{cImage::~cImage()
{}
cImage::cImage()
{}}/*image_real_proxy.cpp*/
#include "image_real_proxy.hpp"
#include <stdio.h>namespace __proxy{cImageReal::cImageReal(std::string const &filename)
{_M_filename = filename;loadFromDisk(_M_filename);
}
void cImageReal::display()
{printf("Displaying %s\n", _M_filename.c_str() );
}
void cImageReal::loadFromDisk(std::string const &filename)
{printf("Loading %s ... ok!\n", _M_filename.c_str() );
}}namespace __proxy{cImageProxy::cImageProxy(std::string const &filename)
{_M_filename = filename;
}
void cImageProxy::display()
{if( nullptr == _M_image ){_M_image = new cImageReal(_M_filename);}if( _M_image != nullptr){_M_image->display();}
}}
3) 用户使用
#include "image.hpp"
#include <cstdlib>
#include <cstdio>int main(int argc, char *argv[])
{if( argc != (1 + 1) ){fprintf(stderr, "Usage:%s <display-times>\n", argv[0]);return EXIT_FAILURE;}long long DISPLAY_TIMES = atoll(argv[1]);__proxy::cImage *image = new __proxy::cImageProxy("test_18mb.jpg");if( image != NULL){printf("---------------------------------\n");image->display();printf("---------------------------------\n");for(long long idisp = 1; idisp < DISPLAY_TIMES; idisp++ ){image->display();}delete image, image = NULL;}return EXIT_SUCCESS;
}
4) 编译与运行