zoukankan      html  css  js  c++  java
  • C#

    适配器模式

    问题场景

    学生需要一名英语老师,但英语老师暂时还没有就职,只能暂时由校长代替这个职位。可是学生明确要求要一名教授英语的老师(必须是实现了ITeacher接口的老师),此时为了哄骗学生,我们只能将校长伪造成一名英语教师代替执行教学任务。伪造的工作交给适配器来完成,适配器实现了ITeacher接口,所以学生能看见的就是适配器而非校长,而适配器内部就是调用校长来执行任务的,只不过学生根本不知道而已。

    总结模式

    客户期望的一个接口类型的实例来完成任务,但该接口类型暂时没有一个具体的实现,所以使用适配器去调用另一种类型的方法来解决问题。

    示例代码

    public interface ITeacher
    {
        void Teaching( );
    }

    public interface IPrincipal
    {
        void Education( );
    }

    public class Principal : IPrincipal
    {
        public void Education( )
        {
            Console.WriteLine( "上课" );
        }
    }

    public class TeachAdapter : ITeacher
    {
        private IPrincipal principal;
        public TeachAdapter( IPrincipal principal ) { this.principal = principal; }
        public void Teaching( )
        {
            principal.Education( );
        }
    }

    public class Programe
    {
        static void Main( string[] args )
        {
            ITeacher teacher = new TeachAdapter( new Principal( ) ); //客户要求ITeacher去执行任务,我就去找另一个类型来执行任务,反正客户是不会知道的
            teacher.Teaching( );
        }
    }

     

    C# - 设计模式目录

  • 相关阅读:
    多线程实际应用踩坑
    SpringBoot远程接口调用-RestTemplate使用
    Python测试Post请求
    Ubuntu基于zsh自定义设置shell主题
    github-share报错无法读取远程仓库
    JVM是如何处理异常的
    springboot之父pom操作
    php 后台json 转 js数组
    tp 外连接查询
    原生关联查询语句
  • 原文地址:https://www.cnblogs.com/myrocknroll/p/8596901.html
Copyright © 2011-2022 走看看