適配器模式(Adapter Pattern)又稱變壓器模式或者包裝模式:
定義:Convert the interface of a class into another interface clints expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces。(將一個類的接口編程客戶端所期待的另一種接口,從而使原本因接口不匹配而無法在一起工作的兩個類能夠在一起工作。)
通用類圖:
Target目標角色:該角色定義其他類轉換成我們期待的類或接口
Adaptee源角色:你想把誰變成目標角色,這個“誰”就是源角色
Adapter適配器角色:適配器的核心角色,其他兩個角色都是已經存在的角色,而適配器角色需要新建立的,它的職責非常簡單,就是通過繼承或者類關聯的方式把源角色轉換成目標角色
優點
1、通過適配器,客戶端可以調用同一接口,因而對客戶端來說是透明的。這樣做更簡單、更直接、更緊湊。
2、 復用了現存的類,解決了現存類和復用環境要求不一致的問題。
3 、將目標類和適配者類解耦,通過引入一個適配器類重用現有的適配者類,而無需修改原有代碼。
4、 一個對象適配器可以把多個不同的適配者類適配到同一個目標,也就是說,同一個適配器可以把適配者類和它的子類都適配到目標接口。
缺點
對于對象適配器來說,更換適配器的實現過程比較復雜。
//機器人類 abstract public class Robot { abstract public void RobotCry(); abstract public void RobotMove(); abstract public void SetAdaptee(object Value); //這么申明帶有一個參數的抽象方法。 } //抽象的Adaptee public class AnimalAdaptee { public virtual void Cry() { } public virtual void Move() { } } //不同種類的動物 //狗 public class DogAdaptee : AnimalAdaptee { public override void Cry() { //base.Cry(); Console.WriteLine("這是狗叫:汪汪汪!"); } public override void Move() { //base.Move(); Console.WriteLine("這是狗跳:跳跳跳!"); } } //鳥 public class BirdAdaptee : AnimalAdaptee { public override void Cry() { //base.Cry(); Console.WriteLine("這是鳥叫:嘰嘰嘰!"); } public override void Move() { //base.Move(); Console.WriteLine("這是鳥飛:快快飛!"); } } //適配器類Adaptor public class RobotAdaPPTor : Robot { PRivate AnimalAdaptee _myAdaptee; public AnimalAdaptee MyAdaptee { get { return _myAdaptee; } set { _myAdaptee = value; } } public override void SetAdaptee(Object Value) { _myAdaptee = (AnimalAdaptee)Value; } public override void RobotCry() { //throw new NotImplementedException(); if (_myAdaptee == null) _myAdaptee = new AnimalAdaptee(); _myAdaptee.Cry(); } public override void RobotMove() { //throw new NotImplementedException(); if (_myAdaptee == null) _myAdaptee = new AnimalAdaptee(); _myAdaptee.Move(); } } class Program { static void Main(string[] args) { Robot MyRobot = new RobotAdapptor(); AnimalAdaptee dogAdaptee = new DogAdaptee(); MyRobot.SetAdaptee(dogAdaptee); MyRobot.RobotCry(); MyRobot.RobotMove(); //申明為第二種鳥類 AnimalAdaptee birdAdaptee=new BirdAdaptee(); MyRobot.SetAdaptee(birdAdaptee); MyRobot.RobotCry(); MyRobot.RobotMove(); Console.ReadKey(); } }好了,這一章就寫到這,歡迎大家加入QQ群:280993838 。或者關注我的公眾號:
新聞熱點
疑難解答