Home Backend Development C#.Net Tutorial .NET adapter pattern explained

.NET adapter pattern explained

Dec 20, 2016 pm 01:12 PM
adapter mode

Introduction to the adapter pattern:

Convert the interface of a class into another interface that the customer wants. The Adapter pattern enables classes that would otherwise not work together due to incompatible interfaces to work together.

In computer programming, the adapter pattern (sometimes also called wrapper style or wrapper) adapts the interface of a class to what the user expects. An adaptation allows classes that normally wouldn't work together because of incompatible interfaces to work together by wrapping the class's own interface in an existing class.

Adapter pattern structure diagram:

.NET adapter pattern explained

Introducing an example to illustrate:

Using the logging program as the demo description, there will be a corresponding log management module in any set of software. If we develop a log in the software Recording uses a third-party log component for logging, which uses the Log.Write("write log"); method. During development of our program, a large number of diary recording objects are instantiated, using the Log.Write() method. Logging, but now third-party logging components are no longer free and need to be charged, so we plan to use a new log management module, but the API interface it provides us uses Log.WriteLog("New Write Log method"); perform logging. At this time, the question arises, how to deal with this migration change

Class Adapter Mode

1. The original log interface used the Write ("write log"); method

/// <summary>
/// 原来的日志记录接口
/// </summary>
public interface ILogTarget
{
  /// <summary>
  /// 原来的写日志方法
  /// </summary>
  void Write(string info);
}
Copy after login
Copy after login

2. However, the current log writing interface The interface uses WriteLog ("write log"); it implements a new way of writing logs: writing logs to files and databases

/// <summary>
/// 抽象写日志类
/// </summary>
public abstract class LogAdaptee
{
  /// <summary>
  /// 写日志
  /// </summary>
  public abstract void WriteLog(string info);
}
Copy after login
Copy after login
/// <summary>
/// 写文件日志记录
/// </summary>
public class FileLog:LogAdaptee
{
  /// <summary>
  /// 写日志到文件中
  /// </summary>
  public override void WriteLog(string info)
  {
    Console.WriteLine("记录到文本文件:"+info);
  }
}
Copy after login
Copy after login
/// <summary>
/// 往数据库中写日志
/// </summary>
public class DatabaseLog:LogAdaptee
{
  /// <summary>
  /// 重写写日志方法
  /// </summary>
  public override void WriteLog(string info)
  {
    Console.WriteLine("记录到数据库:"+info);
  }
}
Copy after login
Copy after login

3. How to use two new objects way to replace the original way of writing logs?

/// <summary>
/// 采用新的写日志的方式,写入到数据库中
/// </summary>
public class DatabaseLogAdapter:DatabaseLog,ILogTarget
{
  /// <summary>
  /// 在重写ILogTarget接口中的的Write方法里面调用新的写日志的方式WriteLog
  /// </summary>
  public void Write(string info)
  {
    WriteLog(info);
  }
}
Copy after login
/// <summary>
/// 采用新的写日志的方式,写入到文本文件
/// </summary>
public class FileLogAdapter : FileLog, ILogTarget
{
  /// <summary>
  /// 在重写ILogTarget接口中的的Write方法里面调用新的写日志的方式WriteLog
  /// </summary>
  public void Write(string info)
  {
    this.WriteLog(info);
  }
}
Copy after login

4. The original logging method is used, but the new logging method is indeed used:

/// <summary>
/// 类 .NET adapter pattern explained(Adapter Pattern)
/// </summary>
class Program
{
  static void Main(string[] args)
  {
    ILogTarget dbLog = new DatabaseLogAdapter();
    dbLog.Write("程序启动成功");
    dbLog = new FileLogAdapter();
    dbLog.Write("程序启动成功");
  }
}
Copy after login

Object Adapter Pattern

1. The method uses a class adapter The migration changes of the new log function are implemented in this way. Next, we use the object adapter to distinguish the special features of the two methods. The original method of writing logs remains the same: Write("Write Log");

/// <summary>
/// 原来的日志记录接口
/// </summary>
public interface ILogTarget
{
  /// <summary>
  /// 原来的写日志方法
  /// </summary>
  void Write(string info);
}
Copy after login
Copy after login

2. The current log writing interface uses WriteLog("Write Log"); it implements the function of writing logs New way: write logs to files and databases:

/// <summary>
/// 抽象写日志类
/// </summary>
public abstract class LogAdaptee
{
  /// <summary>
  /// 写日志
  /// </summary>
  public abstract void WriteLog(string info);
}
Copy after login
Copy after login
/// <summary>
/// 写文件日志记录
/// </summary>
public class FileLog:LogAdaptee
{
  /// <summary>
  /// 写日志到文件中
  /// </summary>
  public override void WriteLog(string info)
  {
    Console.WriteLine("记录到文本文件:"+info);
  }
}
Copy after login
Copy after login
/// <summary>
/// 往数据库中写日志
/// </summary>
public class DatabaseLog:LogAdaptee
{
  /// <summary>
  /// 重写写日志方法
  /// </summary>
  public override void WriteLog(string info)
  {
    Console.WriteLine("记录到数据库:"+info);
  }
}
Copy after login
Copy after login

3. Above we added the FileLogAdapter class, the DatabaseLogAdapter class, which inherits the FileLog, DatabaseLog, and ILogTarget interfaces, and overrides the Write method to call the new The method of writing logs is WriteLog. Migration changes have been carried out using this method. Object adaptation is used below:

/// <summary>
/// 对象适配,继承ILogTarget,里面有LogAdaptee抽象日志类对象。
/// </summary>
public class LogAdapter:ILogTarget
{
  /// <summary>
  /// 抽象写日志类
  /// </summary>
  private LogAdaptee _adaptee;
 
  public LogAdapter(LogAdaptee adaptee)
  {
    this._adaptee = adaptee;
  }
 
  public void Write(string info)
  {
    _adaptee.WriteLog(info);
  }
}
Copy after login

4. Call in the program:

/// <summary>
/// 对象.NET adapter pattern explained(Adapter Pattern)
/// </summary>
class Program
{
  static void Main(string[] args)
  {
    ILogTarget dbLog = new LogAdapter(new DatabaseLog());
    dbLog.Write("程序启动成功");
    ILogTarget fileLog = new LogAdapter(new FileLog());
    fileLog.Write("程序启动成功");
  }
}
Copy after login

Compare the migration changes of the two. In the class adaptation method, we get the adapter classes DatabaseLogAdapter and FileLogAdapter It has all the behaviors of the parent class it inherits, and also has all the behaviors of the interface ILogTarget. This actually violates the single responsibility principle of classes in the object-oriented design principles, while the object adapter is more in line with the object-oriented spirit, so Class adaptation is not recommended in practical applications. Assume that the adapted class we want to write to the file and database at the same time when recording logs, then using the object adapter we will write like this:

/// <summary>
/// 对象适配,继承ILogTarget,里面有LogAdaptee抽象日志类对象。
/// </summary>
public class LogAdapter:ILogTarget
{
  /// <summary>
  /// 抽象写日志类
  /// </summary>
  private LogAdaptee _adapteed;
 
  /// <summary>
  /// 抽象写日志类
  /// </summary>
  private LogAdaptee _adapteef;
 
  public LogAdapter(LogAdaptee adapteed, LogAdaptee adapteef)
  {
    this._adapteed = adapteed;
    this._adapteef = adapteef;
  }
 
  public void Write(string info)
  {
    _adapteed.WriteLog(info);
    _adapteef.WriteLog(info);
  }
}
Copy after login

Call:

/// <summary>
/// 对象.NET adapter pattern explained(Adapter Pattern)
/// </summary>
class Program
{
  static void Main(string[] args)
  {
    //同时写日志到文件和数据库
    ILogTarget dbLog = new LogAdapter(new FileLog(), new DatabaseLog());
    dbLog.Write("程序启动成功");
  }
}
Copy after login

If we use a class adapter instead : Can we use this way of writing to achieve our goal?

public class DatabaseLogAdapter : DatabaseLog, FileLog, ILogTarget
{
  public void Write(string info)
  {
    this.WriteLog(info);
  }
}
Copy after login

The result is definitely not possible. A class cannot have multiple base classes. It is wrong to write the details like this. For different situations, we should adopt appropriate methods for adaptive scheduling.

The above is the entire content of this article. I hope it will be helpful to everyone’s learning. I also hope that everyone will support the PHP Chinese website.


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1255
29
C# Tutorial
1228
24
C# .NET Interview Questions & Answers: Level Up Your Expertise C# .NET Interview Questions & Answers: Level Up Your Expertise Apr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

Testing C# .NET Applications: Unit, Integration, and End-to-End Testing Testing C# .NET Applications: Unit, Integration, and End-to-End Testing Apr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

C# .NET: Exploring Core Concepts and Programming Fundamentals C# .NET: Exploring Core Concepts and Programming Fundamentals Apr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

From Web to Desktop: The Versatility of C# .NET From Web to Desktop: The Versatility of C# .NET Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

The Continued Relevance of C# .NET: A Look at Current Usage The Continued Relevance of C# .NET: A Look at Current Usage Apr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Apr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

Is C# .NET Right for You? Evaluating its Applicability Is C# .NET Right for You? Evaluating its Applicability Apr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# .NET Security Best Practices: Preventing Common Vulnerabilities C# .NET Security Best Practices: Preventing Common Vulnerabilities Apr 05, 2025 am 12:01 AM

Security best practices for C# and .NET include input verification, output encoding, exception handling, as well as authentication and authorization. 1) Use regular expressions or built-in methods to verify input to prevent malicious data from entering the system. 2) Output encoding to prevent XSS attacks, use the HttpUtility.HtmlEncode method. 3) Exception handling avoids information leakage, records errors but does not return detailed information to the user. 4) Use ASP.NETIdentity and Claims-based authorization to protect applications from unauthorized access.

See all articles