The decorator mode, also called the adorner mode. As the name implies, is to wrap a layer of objects, packaging. Let it become the object of your liking. This pattern is often used in our development, and it is a technique to deal with problems, that is, to not let the program be inflexible or to extend the program.
(i) When to use it ""
1. You need to give the class an extension, or attach a responsibility to the class.
2. Dynamically add a feature to the class that can be revoked dynamically.
3. When you cannot extend by subclasses.
In this article, we illustrate with the main example of the year.
(ii) The structure of the adorner ""
IAction: The adorner standard interface, which is fitted with an adorner, is implemented.
Delegateaction: Decorative class, used to implement the function of the iaction socket, and provide another form of representation to the outside.
Standardaction: Standard implementation class, used to implement the function of the iaction socket, the display is also based on the IAction interface
Implement: External public call class, it exposes two interface methods to the outside, one is the IAction interface standard, the first is the action<int> entrusted standard.
C # Implementation of adorners
IAction.cs
#region decorated mode public interface iaction { void pring ( int a); } #endregion
DelegateAction.cs
Public class delegateaction:iaction { Action<int> _action; Public void Pring (int a) { _action (a); } Public Delegateaction (action<int> action) { = action; } }
Implement.cs
Public class Implement { publicvoid Run (iaction action) { action. Pring (ten); } Public void Run (action<int> action) { new delegateaction (action). Pring (ten); } }
StandarAction.cs
Public class standaraction:iaction { publicvoid pring (int a) { Console.Write (" Standard Implementation Decorator "+a); } }
Call:
Static void Main (string[] args) { new Implement (); = Console.Write (a)); Implement. Run (new standaraction ()); }
The visible extension method can make the adornment behavior very concise, looks like the object itself has the new method. Also avoids the program to appear many adornment object, simplifies the procedure.