一个懒加载Demo

2019-04-07  本文已影响0人  TimeMage

什么是懒加载

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

代码

//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成功
上一篇下一篇

猜你喜欢

热点阅读