30-21 之 Domain Layer - Lazy Load ( 未完成 )

什麽是 Lazy Load 呢 ?

An object that doesn’t contain all of the data you need but knows how to get it.

简单的想你可以想成有一个很大的 Object S,然後里面有 A、B、C 栏位,每个里面都还是一个很大包的 Object,而 Lazy Load 就是可以在读取 S.A 的资料时,可以只需要将 S.A 载入到记忆体,而不用整个 S 都要载入到记忆体中。

在书中有提到四种方式,然後右边箭头代表适用的模式 :

  • lazy initialization → active record、table data gateway、row data gateway
  • virtual proxy → data mapper
  • value holder → domain model
  • ghost → Identity Map

接下来由范例来说明每种模式的样子。

每一次访问属性时,先判断有没有,如果为空,则在去 load 值。( 怎麽感觉好像 cache ),但这也代表要访问属性时,需要透过方法。

Inheritance → Lazy Loading 常见问题

多余的资料库处理 → ripple loading

This will cause you to go to the database once for each object instead of reading them all in at once.

范例

Lazy initialization

下面这个是书中的范例,但我第一眼看到时冒出两个问题 :

  • 这感觉不就是 cache 吗 ? 那如果 findForSupplier 的资料有更新怎麽办 ?
  • 这范例感觉比较像 cache 吧 ? 感觉和 Lazy Loading 不要全部载入有点不太一样呢 ?
class Supplier...
	public List getProducts() {
		if (products == null) products = Product.findForSupplier(getID()); 
    return products;
	}
}

然後又去找了其它的例如 wiki 的范例,我到觉得比较适合,虽然他和上面书中的范例有点相似,都是去记忆中拿,到这里 new 物件的,事实上应该是不会随这时间而变动,因此应该是不太会有像 cache 更新的问题。

class Fruit {

    private static Map<FruitType, Fruit> types = new HashMap<>();
    
    public static Fruit getFruitByTypeName(FruitType type) {
        Fruit fruit;
        if (!types.containsKey(type)) {
            // Lazy initialisation
            fruit = new Fruit(type);
            types.put(type, fruit);
        } else {
            // OK, it's available currently
            fruit = types.get(type);
        }
        
        return fruit;
    }
}

Virtual Proxy

这里我用 js 简单举个例子,假设我们有多种产品,然後要根据产品类型产生相对应的物件,然後下面就有两种写法,一个是『 全载入 』而另一个就是『 需要那个才载入那个 』。

// 全载入,就算你只要用 COURSE 的方法
const ProductFactory = {
    'ARTICLE': require('./article')
    'COURSE': require('./course')
}

// Lazy Loading,当你需要的使後才 require 该物件
const ProductLazyLoadingFactory = new Proxy(
    {},
    {
      get: (target, prop) => {
        const product = _productFactory(prop)
        return product
      }
    }
  )

  function _productFactory (category) {
    switch (category) {
      case 'ARTICLE':
        return require('./article')
      case 'COURSE':
        return require('./course')
      default:
        throw new Error(`The category#${category} is nonexistent`)
    }
  }

小总结

这个知识点可以用来解释什麽现象

这个知识点可以和以前的什麽知识连结呢 ?

我要如何运用这个知识点 ?

参考资料


<<:  Day21-大量图片的页面(上)_利用grid快速排版

>>:  Day20 - this&Object Prototypes Ch3 Objects - Review 开头

成员 20 人:

撰写中 在求发展的道路上,又过了一日...... 这时,成员 20 人。 ...

【D22】制作讯号灯之反思:观察讯号灯与9/22大盘关系

前言 今天加权指数开低,维持一个大跌,来观察讯号灯和大盘、个股的关系,来验证我们的讯号灯能不能参考。...

DAY19:进阶清单元件之实作

这次要用所做过的范例来说明,首先,基本的设计画面就不多说了! 设计出後第一页会长这样 按下新增联络人...

Day 9 - TiFlash架构(上)

TiDB能做到HTAP的另一块拼图,TiFlash,是以Column为储存模式的,适合用於一次读取少...

Day 08 借箸代筹(2):自动转型、运算子及其後

自动转型 续前文所述,当我们使用两个等号(==)作比较运算时,深受JavaScript「自动转型」的...