在整个.NET Framework中使用了什么设计模式? [英] What design patterns are used throughout the .NET Framework?

查看:139
本文介绍了在整个.NET Framework中使用了什么设计模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

嗯,在.NET Framework中,什么类实现了各种设计模式,如装饰器,工厂等。 ,您的要求可能是一个非常广泛的列表,因为设计模式遍及.NET平台。以下是我能想到的一些例子:



适配器



适配器模式是桥接系统和平台的常用机制,可以通过.NET框架以各种方式实现。 .NET中最流行的一个例子是运行时Callable Wrappers或RCW。使用 tlbimp.exe 程序生成的RCW提供了使.NET托管代码通过.NET API轻松调用到传统COM代码的适配器。



工厂方法



工厂方法模式可能是最好的已知图案它在.NET框架中相当普遍地实现,特别是在原始时代,而且在许多其他框架上。在框架中这个模式的一个很好的例子是Convert类,它提供了一系列方法来创建其他常见原语的公共原语。



另外,另一种普遍的形式这种模式是在许多原始和基本类型上找到的.Parse()和.TryParse()方法。



迭代器



实现 Iterator 通过几个接口和一些语言结构,如foreach和在C#中的yeild关键字。 IEnumerable 界面及其通用对话由几十个集合在.NET框架,允许对各种各样的数据集进行简单,动态的迭代:

  IEnumerable< T> 
IEnumerator< T>

foreach(var thing in someEnumerable)
{
//
}

C#中的 yeild 关键字允许实现迭代器的真实形式,只需承担费用当需要迭代时,通过循环处理迭代:

  IEnumerable< string> TokenizeMe(string complexString)
{
string [] tokens = complexString.Split('');
foreach(string token in toekens)
{
yield return token;
}
}

生成器



在.NET框架中实现了 Builder 模式几次。一些注释是连接字符串构建器。连接字符串可以是一个挑剔的事情,并且在运行时动态构造它们有时可能是一种痛苦。 Connection String Builder类理想地演示了构建器模式:

  string connectionString = new SqlConnectionStringBuilder 
{
DataSource = localhost,
InitialCatalog =MyDatabase,
IntegratedSecurity = true,
Pooling = false
} .ConnectionString;

.NET框架中的其他类,如UriBuilder,也实现了构建器模式。 >

观察者



观察者模式是一种常见的模式允许一个班级观看另一个课程。从.NET 4开始,这种模式通过两种方式得到支持:通过语言集成事件(紧密耦合的观察者),以及通过IObservable / IObserver接口(松散耦合的事件)。



经典语言事件利用代表或强类型的函数指针,以跟踪事件属性中的事件回调。事件触发时,将按顺序执行每个跟踪的回调。这样的事件在.NET框架中普遍使用。

  public class EventProvider 
{
public event EventHandler SomeEvent;

protected virtual void OnSomeEvent(EventArgs args)
{
if(SomeEvent!= null)
{
SomeEvent(this,args); //触发事件
}
}
}

public class EventConsumer
{
public EventConsumer(EventProvider provider)
{
provider.SomeEvent + = someEventHandler; //注册为事件的观察者
}

private void someEventHandler(EventArgs args)
{
//处理事件
}
}

新的.NET 4框架是松散耦合的事件。这些是通过实现 c /> c $ c>和接口中的 IObservable< out T> IObserver来实现的,其更直接地支持原始的观察者设计模式。虽然我没有直接实现我所知道的任何.NET框架类型,但是该模式的核心基础架构是.NET 4的一个组成部分。

 code> public class SomethingObservable:IObservable< SomethingObservable> 
{
private readonly列表< IObserver< SomethingObservable>> m_observers;

public IDisposable订阅(IObserver< SomethingObservable>观察者)
{
if(!m_observers.Contains(观察者))
{
m_observers.Add观察者);
}
var unsubscriber = new取消订阅者(m_observers,观察者)
返回unsubscriber;
}

private class取消订阅者:IDisposable
{
public取消订阅者(IList< IObserver< SomethingObservable>>观察者,IObserver< SomethingObservable>观察者)
{
m_observers =观察者;
m_observer = observer;
}

私有只读IList< IObserver< SomethingObservable>> m_observers;
private readonly IObserver< SomethingObservable> m_observer;

public void Dispose()
{
if(m_observer == null)return;
if(m_observers.Contains(m_observer))
{
m_observers.Remove(m_observer);
}
}
}
}

strong>装饰器



装饰器模式是通过单个基本类型提供行为的替代表示或形式的一种方法。通常,需要一组通用的功能,但是该功能的实际实现需要改变。 .NET框架中的一个很好的例子是Stream类及其衍生物。 .NET中的所有流都提供相同的基本功能,但每个流的功能不同。







    • MemoryStream

    • BufferedStream

    • FileStream


      • IsolatedStorageFileStream


    • PipeStream


      • AnonymousPipeClientStream

      • AnonymousPipeServerStream

      • NamedPipeClientStream

      • NamedPipeServerStream


    • CryptoStream

    • GZipStream




<在.NET框架中使用许多其他许多设计模式。 .NET的几乎每个方面,从语言到框架到基本的运行时概念都是基于常见的设计模式。 .NET框架的重要部分(如ASP.NET)本身就是模式。例如,ASP.NET MVC框架,它是MVC的Web变体的实现,或者模型 - 视图 - 控制器。 WPF和Silverlight UI框架直接支持称为MVVM的模式,或者Model-View-ViewModel 。 ASP.NET管道本身是一组模式,包括截取过滤器,页面控制器,路由器等。最后,最多常用的模式,组合在.NET框架中被广泛使用,它可能是整个框架最基本的模式之一。


What classes in the .NET Framework implement the various design patterns such as decorator, factory, etc.?

解决方案

Well, what your asking for is probably a VERY extensive list, as design patterns are use all over the .NET platform. Here are some examples I can think of off the top of my head:

Adapter

The adapter pattern, a common mechanism of bridging systems and platforms, is implemented in a variety of ways in the .NET framework. One of the most prevalent examples of this in .NET are Runtime Callable Wrappers, or RCW's. RCW's, generated with the tlbimp.exe program, provide adapters that let .NET managed code easily call into legacy COM code via a .NET API.

Factory Method

The factory method pattern is probably one of the most well-known patterns. It is implemented quite commonly throughout the .NET framework, particularly on primitive times, but also on many others. An excellent example of this pattern in the framework is the Convert class, which provides a host of methods to create common primitives from other common primitives.

Additionally, another pervasive form of this pattern are the .Parse() and .TryParse() methods found on many primitive and basic types.

Iterator

The Iterator pattern is implemented via a couple interfaces and some language constructs, like foreach and the yeild keyword in C#. The IEnumerable interface and its generic counterpart are implemented by dozens of collections in the .NET framework, allowing easy, dynamic iteration of a very wide variety of data sets:

IEnumerable<T>
IEnumerator<T>

foreach(var thing in someEnumerable)
{
   //
}

The yeild keyword in C# allows the true form of an iterator to be realized, only incurring the cost of processing an iteration through a loop when that iteration is demanded:

IEnumerable<string> TokenizeMe(string complexString)
{
    string[] tokens = complexString.Split(' ');
    foreach (string token in toekens)
    {
        yield return token;
    }
}

Builder

The Builder pattern is implemented a few times in the .NET framework. A couple of note are the connection string builders. Connection strings can be a picky thing, and constructing them dynamically at runtime can sometimes be a pain. Connection String Builder classes demonstrate the builder pattern ideally:

string connectionString = new SqlConnectionStringBuilder
{
    DataSource = "localhost",
    InitialCatalog = "MyDatabase",
    IntegratedSecurity = true,
    Pooling = false
}.ConnectionString;

Other classes throughout the .NET framework, such as UriBuilder, also implement the builder pattern.

Observer

The observer pattern is a common pattern that allows one class to watch events of another. As of .NET 4, this pattern is supported in two ways: via language-integrated events (tightly coupled observers), and via the IObservable/IObserver interfaces (loosely coupled events).

Classic language events make use of delegates, or strongly-typed function pointers, to track event callbacks in event properties. An event, when triggered, will execute each of the tracked callbacks in sequence. Events like this are used pervasively throughout the .NET framework.

public class EventProvider
{
    public event EventHandler SomeEvent;

    protected virtual void OnSomeEvent(EventArgs args)
    {
        if (SomeEvent != null)
        {
            SomeEvent(this, args); // Trigger event
        }
    }
}

public class EventConsumer
{
    public EventConsumer(EventProvider provider)
    {
        provider.SomeEvent += someEventHandler; // Register as observer of event
    }

    private void someEventHandler(EventArgs args)
    {
        // handle event
    }
}

New with the .NET 4 framework are loosely coupled events. These are accomplished by implementing the IObservable<out T> and IObserver<in T> interfaces, which more directly support the original Observer design pattern. While not directly implemented by any .NET framework types that I am aware of, the core infrastructure for the pattern is an integral part of .NET 4.

public class SomethingObservable: IObservable<SomethingObservable>
{
    private readonly List<IObserver<SomethingObservable>> m_observers;

    public IDisposable Subscribe(IObserver<SomethingObservable> observer)
    {
        if (!m_observers.Contains(observer))
        {
            m_observers.Add(observer);
        }
        var unsubscriber = new Unsubscriber(m_observers, observer)
        return unsubscriber;        
    }

    private class Unsubscriber: IDisposable
    {
        public Unsubscriber(IList<IObserver<SomethingObservable>> observers, IObserver<SomethingObservable> observer)
        {
            m_observers = observers;
            m_observer = observer;
        }

        private readonly IList<IObserver<SomethingObservable>>  m_observers;
        private readonly IObserver<SomethingObservable> m_observer;

        public void Dispose()
        {
            if (m_observer == null) return;
            if (m_observers.Contains(m_observer))
            {
                m_observers.Remove(m_observer);
            }
        }
    }
}

Decorator

The decorator pattern is a way of providing alternative representations, or forms, of behavior through a single base type. Quite often, a common set of functionality is required, but the actual implementation of that functionality needs to change. An excellent example of this in the .NET framework is the Stream class and its derivatives. All streams in .NET provide the same basic functionality, however each stream functions differently.

  • Stream
    • MemoryStream
    • BufferedStream
    • FileStream
      • IsolatedStorageFileStream
    • PipeStream
      • AnonymousPipeClientStream
      • AnonymousPipeServerStream
      • NamedPipeClientStream
      • NamedPipeServerStream
    • CryptoStream
    • GZipStream

Many, many other design patterns are used within the .NET framework. Almost every aspect of .NET, from language to framework to fundamental runtime concepts, are based on common design patterns. Significant portions of the .NET framework, such as ASP.NET, are in and of themselves patterns. Take, for example, the ASP.NET MVC framework, which is an implementation of the web variant of MVC, or Model-View-Controller. The WPF and Silverlight UI frameworks directly support a pattern called MVVM, or Model-View-ViewModel. The ASP.NET pipeline itself is a collection of patterns, including intercepting filter, page controller, router, etc. Finally, one of the most commonly used patterns, composition, is used so extensively in the .NET framework that it is probably one of the most fundamental patterns of the entire framework.

这篇关于在整个.NET Framework中使用了什么设计模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆