CSharp: Lazy Load Pattern in donet core 6
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Geovin.Du.DuLazyLoad.DuVirtualProxy { /// <summary> /// Lazy Load Pattern /// </summary> public class College { /// <summary> /// 序号 /// </summary> public int Id { get; init; } /// <summary> /// 图书馆信息 /// </summary> public virtual Library? Library { get; set; } /// <summary> /// /// </summary> public void ShowDetails() => Console.WriteLine( $"大学图书馆有 {Library!.NumberOfBooks} 本书 " + $"创建时间为:{Library.EstablishmentDate.ToShortDateString()}."); } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Geovin.Du.DuLazyLoad.DuVirtualProxy { /// <summary> /// Lazy Load Pattern /// </summary> public class CollegeFactory { /// <summary> /// /// </summary> /// <param name="id"></param> /// <returns></returns> public College CreateFromId(int id) => new ProxyCollege(id); } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Geovin.Du.DuLazyLoad.DuVirtualProxy { /// <summary> /// /// </summary> public class ProxyCollege : College { /// <summary> /// Lazy Load Pattern /// </summary> /// <param name="id"></param> public ProxyCollege(int id) { Id = id; Console.WriteLine("学院信息初始化完成."); } /// <summary> /// /// </summary> public override Library? Library { get { if (base.Library == null) { base.Library = new Library(); } return base.Library; } set => base.Library = value; } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object? obj) { if (obj is not College college) { return false; } return college.Id == Id; } /// <summary> /// /// </summary> /// <returns></returns> public override int GetHashCode() => Id.GetHashCode(); } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Geovin.Du.BuildingBlocks; namespace Geovin.Du.DuLazyLoad.DuVirtualProxy { /// <summary> /// Lazy Load Pattern /// </summary> public static class VirtualProxyExecutor { public static void Execute() { ConsoleExtension.WriteSeparator("延迟加载模式 Lazy Load Pattern--Virtual proxy demo"); var collegeFactory = new CollegeFactory(); var college = collegeFactory.CreateFromId(1); // College library shouldn't have been constructed before calling ShowDetails method. Console.WriteLine("给我更多关于这所大学的细节!"); college.ShowDetails(); } } }
调用:
Geovin.Du.DuLazyLoad.DuVirtualProxy.VirtualProxyExecutor.Execute();
输出:
延迟加载模式 Lazy Load Pattern--Virtual proxy demo -------------------------------------------------- 学院信息初始化完成. 给我更多关于这所大学的细节! 加载库... 大学图书馆有 210000 本书 创建时间为:2008/5/28.
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)