zoukankan      html  css  js  c++  java
  • 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 ();
        }
    }
  • 相关阅读:
    EF fluent API如何配置主键不自动增长
    简单的自定义Session
    使用NPOI,完成数据的导入导出
    c#索引器
    MUI框架 picker日期选择器实例
    使用MUI框架,模拟手机端的下拉刷新,上拉加载操作。
    Newtonsoft.Json
    NetMQ:.NET轻量级消息队列
    C#之RabbitMQ系列(一)
    C# 核心语法-反射(反射类型、方法、构造函数、属性,实现可配置可扩展,完成数据库访问类反射封装)
  • 原文地址:https://www.cnblogs.com/Jason-c/p/8872175.html
Copyright © 2011-2022 走看看