美文网首页
一个懒加载Demo

一个懒加载Demo

作者: TimeMage | 来源:发表于2019-04-07 20:45 被阅读0次

    什么是懒加载

    当一个实例,生成时并未初始化,只有在调用行为后才会被初始化,即为懒加载

    代码

    //Student.cpp
    #include<iostream>
    #include<string>
    #include<memory>
    using namespace std;
    class AbstractStudent{
        public:
        virtual string getName()=0;
        virtual void setName(string)=0;
    };
    typedef std::shared_ptr<AbstractStudent> Ptr;
    
    class Student:public AbstractStudent{
        private:
        string name;
        
        public:
        Student(string name="") {
            this->name = name;
            cout<< "初始化Student:"+this->name+"成功"<<endl;
        }
        ~Student() {
            cout<< "销毁Student:"+name+"成功"<<endl;
        }
        virtual string getName() {
            return name;
        }
        virtual void setName(string name) {
            this->name = name;
        }
    };
    
    #include "Student.cpp"
    #include <string>
    class LazyInitializer{
        private:
        Ptr target;
        std::string param;
        
        public:
        LazyInitializer(std::string param="") {
            target.reset();
            this->param = param;
        }
        Ptr getStudent() {
            if(!target.get()) {
                target = make_shared<Student>(param);
            }
            return target;
        }
    };
    
    #include "LazyInitializer.cpp"
    #include <string>
    #include <iostream>
    class StudentProxy: public AbstractStudent {
        private:
            LazyInitializer li;
        public:
            StudentProxy(LazyInitializer l) {
                li = l;
            }
            Ptr target() {
                return li.getStudent();
            }
            string getName() {
                return target()->getName();
            }
            void setName(string name) {
                target()->setName(name);
            }
    };
    
    int main() {
        Ptr p = make_shared<StudentProxy>(LazyInitializer("Ken"));
        std::cout<< "step 1\n";
        std::cout<< p->getName()<<std::endl;
        std::cout<< "step 2\n";
        return 0;
    }
    

    输出结果

    step 1
    初始化Student:Ken成功
    Ken
    step 2
    销毁Student:Ken成功
    

    相关文章

      网友评论

          本文标题:一个懒加载Demo

          本文链接:https://www.haomeiwen.com/subject/nmreiqtx.html