设计模式系列6:适配器模式(Adapter Pattern)
生活随笔
收集整理的這篇文章主要介紹了
设计模式系列6:适配器模式(Adapter Pattern)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
定義
將一個類的接口轉換成客戶希望的另一個接口,適配器模式使得原本由于接口不兼容而不能一起工作的那些類可以一起工作。??? --《設計模式》GoF
UML類圖
使用場景
關鍵組成部分
1,目標角色(Target):定義Client使用的與特定領域相關的接口。
2,客戶角色(Client):與符合Target接口的對象協同。
3,被適配角色(Adaptee):定義一個已經存在并已經使用的接口,這個接口需要適配。
4,適配器角色(Adapter):適配器模式的核心,它將對被適配Adaptee角色已有的接口轉換為目標角色Target匹配的接口。對Adaptee的接口與Target接口進行適配。
C#代碼實現
using System;namespace DoFactory.GangOfFour.Adapter.Structural {/// <summary>/// MainApp startup class for Structural/// Adapter Design Pattern./// </summary>class MainApp{/// <summary>/// Entry point into console application./// </summary>static void Main(){// Create adapter and place a request Target target = new Adapter();target.Request();// Wait for user Console.ReadKey();}}/// <summary>/// The 'Target' class/// </summary>class Target{public virtual void Request(){Console.WriteLine("Called Target Request()");}}/// <summary>/// The 'Adapter' class/// </summary>class Adapter : Target{private Adaptee _adaptee = new Adaptee();public override void Request(){// Possibly do some other work// and then call SpecificRequest _adaptee.SpecificRequest();}}/// <summary>/// The 'Adaptee' class/// </summary>class Adaptee{public void SpecificRequest(){Console.WriteLine("Called SpecificRequest()");}} }運行結果:
轉載于:https://www.cnblogs.com/mcgrady/p/10370125.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的设计模式系列6:适配器模式(Adapter Pattern)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: anaconda的简单使用教程(虚拟环境
- 下一篇: ASP.NET MVC 后台传值前端乱码