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 ();
    }
}
原文地址:https://www.cnblogs.com/Jason-c/p/8872175.html