Unity C# 设计模式(七)适配器模式
定义:
将一个类的接口转换成客户希望的另一个接口。adapter模式使得原本由于接口不兼容而不能在一起的那些类可以一起工作。
示例代码:
1、类适配器
/* Class Adapter:类适配器,这里简写为CA 通过适配器PowerAdapter_CA类,将两孔插头TwoHole_CA类进行封装, 从而得到我们想要的三孔插头ITargetThreeHole_CA类, */ public interface ITargetThreeHole_CA { void Request(); }
using UnityEngine; public class TwoHole_CA { public void SpecificRequest() { Debug.Log ("我是两孔的插头"); } }
using UnityEngine; public class PowerAdapter_CA : TwoHole_CA,ITargetThreeHole_CA { public void Request () { Debug.Log ("将"); SpecificRequest (); Debug.Log ("转换为三孔插头了"); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Client_CA : MonoBehaviour { void Start () { ITargetThreeHole_CA threeHole = new PowerAdapter_CA (); threeHole.Request (); } }
2、对象适配器
/* Object Adapter:对象适配器,这里简写为OA 通过适配器ITargetThreeHole_OA类,将两孔插头TwoHole_OA类进行封装, 从而得到我们想要的三孔插头PowerAdapter_OA类, */ public interface ITargetThreeHole_OA { void Request(); }
using UnityEngine; public class TwoHole_OA { public void SpecificRequest() { Debug.Log ("我是两孔的插头"); } }
using UnityEngine; public class PowerAdapter_OA : ITargetThreeHole_OA { TwoHole_OA twoHoleAdaptee=new TwoHole_OA(); public void Request () { Debug.Log ("将"); twoHoleAdaptee.SpecificRequest (); Debug.Log ("转换为三孔插头了"); } }
using UnityEngine; public class Client_OA : MonoBehaviour { void Start () { ITargetThreeHole_OA threeHole = new PowerAdapter_OA (); threeHole.Request (); } }
博客园Jason_c微信打赏码
如果本篇文档对你有帮助,打赏Jason_c根华子吧,他的私房钱被老婆没收了,呜呜!
![](https://files-cdn.cnblogs.com/files/Jason-c/%E5%BE%AE%E4%BF%A1%E6%89%93%E8%B5%8F%E7%A0%81.bmp)