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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值