Lazy

 

简单说来,Lazy<T>要实现的就是按“需”创建,而不是按时创建。

我们往往有这样的情景,一个关联对象的创建需要较大的开销,为了避免在每次运行时创建这种家伙,有一种聪明的办法叫做实现“懒对象”,或者延迟加载。

 

 Lazy<T>

Lazy<T, TMetadata>

  

 

Metadata

在数据仓库领域中,元数据被定义为:描述数据及其环境的数据

在软件构造领域,元数据被定义为:在程序中不是被加工的对象,而是通过其值的改变来改变程序的行为的数据。它在运行过程中起着以解释方式控制程序行为的作用。在程序的不同位置配置不同值的元数据,就可以得到与原来等价的程序行为。

 

 

以下是说的 Lazy<T, TMetadata> 

文档来源:http://www.davidhayden.me/2010/01/lazyt-tmetadata-class-in-systemcomponentmodelcomposition.html

Lazy(T, TMetadata) Class in System.ComponentModel.Composition

I talked about Lazy<T> in .NET 4, which is a pretty cool way to handle multi-threaded access to shared resources that are expensive to create. It does the equivalent of double-check locking to make sure that a resource is only instantiated once.

Most of use know about Lazy<T>, but did you know about Lazy<T,TMetadata> in System.ComponentModel.Composition? I didn’t until last night and I think it is pretty darn cool when you want to interrogate some Metadata to decide if you really want to instantiate the resource.


Lazy<T,TMetadata>

Let’s take a hypothetical situation where we have a number of Publisher Services that publish news on our behalf, but they are expensive to instantiate and we really only want to do this if they are indeed online.

We create two interfaces that represent the publisher service and its metadata as such:

public interface IPublisher 

 void Publish(News news); 

public interface IPublisherMetadata 

 bool Online { get; } 
}


 

We can now use these interfaces in a collection of Lazy<IPublisher,IPublisherMetadata> in say a NewsController that is responsible for handling the publishing of news. Inside the actual Publish Action we interrogate the IPublisherMetaData and only instantiate and call those publishers that indeed are online as such:

public class NewsController 

 private readonly IEnumerable<Lazy<IPublisher, IPublisherMetadata>> _publishers; 

 public NewsController(IEnumerable<Lazy<IPublisher, IPublisherMetadata>> publishers) 
 { 
 _publishers = publishers; 
 } 

 public void Publish(News news) 
 { 
 var publishers = _publishers.Where(p => p.Metadata.Online).ToList(); 

 publishers.ForEach(p => p.Value.Publish(news)); 
 } 
}


 

This is brilliant. The Lazy<T,TMetadata> Class will be very handy in those scenarios where you have a number of expensive services that could achieve some end result but you want to filter them based on some configuration setting or runtime value. Very cool.

 

原文地址:https://www.cnblogs.com/ningth/p/1733022.html