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 implement C # Adapter pattern and decorator pattern

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the knowledge of "how to implement the C# adapter pattern and decorator pattern". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations! I hope you can read it carefully and be able to achieve something!

Structural design pattern

The main purpose of the creative design pattern is to solve the problem of creating objects, while the structural design pattern is to solve the problem of the use of existing objects.

Adapter mode

Adapter patterns are easy to understand because they are common in our daily life, such as headset changeover cords, charger adapters, sockets, etc., to give the most common example:

The socket is an adapter that extends one interface to multiple interfaces and converts the double-hole interface on the wall into a three-hole interface. And that's what adapters do: to convert one interface to another that the user expects.

Usage scenario of the adapter:

You need to use the core functions of third-party SDK, but its interfaces or functions do not meet the requirements, so you can use adapters to make them compatible and extended.

With the development of the business, the old interface can no longer meet the requirements, but the rewriting cost is too high, so we can use the adapter to expand the interface function.

Note: adapters are compatible with and extend existing resources, which is a compromise. If possible, try to restructure the system instead of using adapters.

There are two ways to implement the inheritor: inheritance and combination. based on the principle of synthetic reuse, combination is better than inheritance, so the adapter should be implemented by combination as far as possible. The class diagram is as follows:

The implementation code / / the existing old interface is not compatible with the current system public interface IAmericanElectrictService {int Get110VElectric ();} / / adaptee, and needs to be adapted to the SDK public class AmericanElectrictService: IAmericanElectrictService {public int Get110VElectric () {Console.WriteLine ("the voltage in the United States is 110v and can only provide 110V"); return 110 }} / / the existing interface, the current system needs to use this interface public interface IChineseElectricService {int Get220VElectric ();} / / adapter in a combined way / / here is to adapt to the existing interface, so the interface public class AdapterPattern: IChineseElectricService {private readonly IAmericanElectrictService _ service is implemented. Public AdapterPattern (IAmericanElectrictService service) {this._service = service;} public int Get220VElectric () {var electric = this._service.Get110VElectric (); Console.WriteLine ("bang, bang, b }} / / use adapter to convert 110V voltage to 220V public class AdapterRunner: IRunner {public void Run () {/ / in practice, adaptee may be an existing SDK or interface, corresponding to the specific implementation class var americanElectric = new AmericanElectrictService (); var electric = americanElectric.Get110VElectric () through the IOC container Console.WriteLine ($"obtained {electric} V voltage"); Console.WriteLine ("use adapter"); var adapter = new AdapterPattern (americanElectric); electric = adapter.Get220VElectric (); Console.WriteLine ($"{electric} V voltage obtained after using adapter") } / / output /-- / / the voltage in the United States is 110v, which can only provide 110V / / the voltage obtained is 110V / / using the adapter / / the voltage in the United States is 110v, which can only provide 110V. After some operation, the voltage is now converted to 220V / / the 220V voltage summary has been obtained after using the adapter.

Advantages:

Can be extended and compatible with existing classes with high flexibility

The reuse of classes is improved, and the classes that can not be used can be used after adaptation.

Disadvantages:

The adapter is essentially a set of layers, if used too much, it may lead to system confusion, and even the complexity of the set.

Decorator mode

Using inheritance and combination, the pattern that extends the function without changing the existing structure is called the decorator pattern.

The decorator pattern is very similar to the adapter pattern, but the focus is different. The focus of the adapter is on compatibility with existing systems, while the focus of the decorator is on functional expansion. The class diagram of the decorator is as follows:

In the figure above, the basic decorator inherits the abstract class, each decorator inherits the previous decorator, adding functionality step by step, and all decorators use concrete implementation classes because of the need to extend specific functionality.

You can actually see the difference between some decorators and adapters, both adapters and decorators use combinations to wrap existing classes, except that the decorator uses inheritance. The core principle of the decorator is the Richter substitution principle, that is, the parent class must be replaced by the subclass without affecting the existing code.

Implementation code / / Abstract basic class public abstract class AbstractStudent {public abstract void Study ();} / concrete implementation class public class Student: AbstractStudent {public override void Study () {Console.WriteLine ("I'm learning!") ;}} / / basic decorator, do nothing / / Note that it is marked as an abstract class here, based on which subsequent decorators public abstract class BaseDecorator: AbstractStudent {private readonly AbstractStudent _ student; public BaseDecorator (AbstractStudent student) {this._student = student } / / whether to use override or Virtual here depends on whether the AbstractStudent base class is abstract or interface public override void Study () {this._student.Study () Prefix decorator: public class PreDecorator: BaseDecorator {public PreDecorator (AbstractStudent student): base (student) {} public override void Study () {Console.WriteLine ("read a novel before learning"); base.Study () }} / / suffix decorator, what to do after invoking specific functions public class NextDecorator: PreDecorator {public NextDecorator (AbstractStudent student): base (student) {} public override void Study () {base.Study (); Console.WriteLine ("study hard, reward yourself a bag of spicy gluten") }} / / Test code public class DecoratorRunner: IRunner {public void Run () {Console.WriteLine ("basic functions without decorators:"); var student = new Student (); student.Study (); Console.WriteLine (); Console.WriteLine ("use prefix decorators to do something before basic functions"); var preDecorator = new PreDecorator (student) PreDecorator.Study (); Console.WriteLine (); Console.WriteLine ("use the suffix decorator to do something after the prefix decorator function"); / / Note: the prefix decorator passed here extends var nextDecorator = new NextDecorator (student) over the prefix decorator; nextDecorator.Study () }} / output: / do not use the basic functions of the decorator: / / I am learning! / / use the prefix decorator to do something before the basic function / / read a novel before learning / / I am learning! / use the suffix decorator to do something after the prefix decorator function / / read a novel before learning / / I am learning! / / hard work, reward yourself with a bag of spicy gluten

As you can see, the decorator is actually the use of composition + inheritance (implementation) + override to constantly wrap and update objects, so that its function is extended. Decorators are used to replace inherited design patterns, and the main scenarios are as follows:

Want to extend the functionality of the implementation class, but do not want to add too many subclasses

Need to dynamically add and undo features (such as game skills)

The advantages of the decorator are flexibility, low coupling, and will not change the existing structure. The disadvantage is that too much nesting will increase the complexity of the system.

This is the end of the content of "how to implement the C# adapter pattern and decorator pattern". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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