c#设计模式之[适配器模式]

适配器模式的意图就是将一个接口转化为客户需要的接口请求。例如已经存在某方法ClassA.MakeMyLine(Args),很确定的是这个类以及很 成熟,我们在开发ClassB的时候,需要调用该方法,但是ClassB的接口设计师MakeLine(Args)而不是 MakeMyLine(Args),这就需要一种中间的转化:

using System;
using System.Text ;
public class TestAdapter{
    public static void Main() {
        Target Myobj=new Adapter(new Adaptee());
        Myobj.Execute("参数");
    }
};
public abstract class Target{
    public abstract void Execute(string args);
};
public class Adapter:Target{
    public override void Execute(string args){
        this.MyAdaptee.MyExecute(args);
    }
    private Adaptee MyAdaptee;
    public Adapter(Adaptee obj){
        this.MyAdaptee= obj;
    }

};
public class Adaptee{
    public void MyExecute(string args){
        Console.WriteLine("执行实际方法Adaptee.MyExecute({0})",args);
    }
};



  这是公开一个虚类的方法,在使用的过程中为了适配该方法,同时又调用其他类的其他方法,而做的适配器模式代码。

  这里的Target类我做成了abstract class,在实际中,也有可能是

public interface Target{
    void Execute(string args);
};



  这种模式的,相应的

public void Execute(string args)

这个方法不再是override的了。

  实际中,这个模式的用户非常广泛,例如在播放器MPC中,是典型的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值