Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze the unique exquisite generic design pattern of .NET

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to analyze .NET unique exquisite generic design patterns, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can get something.

Although generics have been around for many years, even Java has already introduced generics (although it is syntax sugar), but the programming way of thinking with generics has not been popularized accordingly. On the one hand, because a large number of Framework in the past are still written in the non-generic era, on the other hand, generic design patterns have not been developed, it is time to change.

Let's give an example to illustrate these two points. If we have written the code for network data capture, we should be familiar with this code:

Var request = WebRequest.Create ("http://www.cnblogs.com/") as HttpWebRequest

Or write it this way, it's the same:

Var request = HttpWebRequest.Create ("http://www.cnblogs.com/") as HttpWebRequest

Have you ever wondered why you have to as every time?

There are similar situations, such as the brothers who do image processing will be familiar with:

Var bm = Image.FromFile ("e:\\ me.jpg") as Bitmap

And

Var bm = Bitmap.FromFile ("e:\\ me.jpg") as Bitmap

I thought about it, but I didn't figure it out. The above two writings, both of which call the factory method of the parent class, actually return an instance of a subclass. Obviously, even if you don't know OCP, you should intuitively expect that the implementation of the parent class should not be determined by the subclass. Predecessors who wrote WebRequest and Image may also find it inappropriate to return a subclass instance directly, so they secretly change the return type of the method signature to the parent class.

Although this kind of behavior deserves serious contempt. However, .NET programmers are mostly good students who follow suit, so this problem has not been changed for many years.

The ideal design would be like this: each subclass of the parent class has a separate factory method that returns its own instance. In this way, before the emergence of generics, it is very clumsy and the loss outweighs the gain, but with generics, it can be implemented cleverly.

Taking the mock Image class as an example, Image and BitMap are implemented as follows:

Class Image where T:Image, new () {public string Path {get; set;} public static T FromFile (string path) {return new T () {Path = path};} class Bitmap:Image {}

There is no need for Image's own factory approach.

You can simply test:

Var path = @ "e:\ me.jpg"; var bm = Bitmap.FromFile (path);; Console.WriteLine (bm.Path); Console.WriteLine (bm.GetType () .Name)

The output is as follows:

Path: e:\ me.jpg Type: Bitmap

In order to make you more familiar, let's take another binary tree in the data structure as an example.

Traditional tree node classes, regardless of C/C++/Java, are similar to this:

Class TreeNode {public TreeNode LeftChild {get; set;} public TreeNode RightChild {get; set;} public TreeNode Parent {get; set;} public int Value {get; set;}}

As we all know, there are several kinds of binary trees, AVL tree, B tree, red-black tree and so on. To realize the special binary tree data structure, it is necessary to inherit TreeNode. Because the type of the tree node has a type that is a member of the base class, it is often necessary to cast the type when the subclass manipulates these members, which is more troublesome than the example of Image and WebRequest, which converts the type only when the instance is created.

This is a good opportunity for generic mode to show off, see the implementation of its parent type:

/ Type of the node. / Type of the node value. Class TreeNode where T:TreeNode where K: IComparable {public T LeftChild {get; set;} public T RightChild {get; set;} public T Parent {get; set;} public K Value {get; set;}}

After that, implement any special binary tree structure, such as RBTreeNode represents the red-black tree node, you can do this:

Class RBTreeNode: TreeNode {/ tree node color, whether it is red. / / public bool IsRed {get; set;} public override string ToString () {return this.Value + "," + (this.IsRed? "R": "B");}}

This is the AVL tree:

Class AvlTreeNode: balance of TreeNode {/ public int Balance {get; set;} public override string ToString () {return "Balance:" + Balance + ", Value:" + this.Value;}}

Not only is it fully compliant with OCP principles, but you no longer need as to cast node types.

This is certainly not my initiative, but there are already a lot of such designs in the .NET Framework, such as the IComparable interface. There are also many excellent frameworks that adopt similar designs, such as Boulder's ORM framework NewLife.XCode.

It looks simple, too, but many people are still in the early stages of the birth of an object-oriented language and are not used to using this design pattern. I think this kind of writing is typical and universal enough to get a design pattern, and it is the special advantage and unique charm of .NET.

When it comes to design patterns, the 23 design patterns proposed by GOF have been out of date for many years, and many new patterns have emerged (for example, for concurrent programming, see Wiki Design Pattern). Some of the old patterns have been included in the .NET language features, and some of the pattern implementations have been revamped. Especially after the emergence of generics, the implementation of many patterns can become much simpler and more elegant.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report