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# - 设计模式目录

原文地址:https://www.cnblogs.com/myrocknroll/p/8596901.html