[review]Design Pattern:Adapter

Adapter pattern

Adapter is designed to change an interface to another interface expected by client. which makes the uncompatible types work together.

When we use this pattern

  • We want to reuse the code designed before, which has the  similar functionality to our current situation. but they are not compatible.
  • When we maintain our system, we need some optimization, but some of them are not compatible.

we can find the core for this pattern is to reuse the code when the former interface is not compatible with the current one and dedicated to resove the compatible issue.

Roles in this pattern.

  • Target: in which our current interfaces and functions are defined.
  • Client: the one that uses the target and communicates with the target.
  • Adaptee: the exsiting interface which is uncompatible with the target but with the similar function to the target. we got to use a adapter to adapt it into our target.
  • Adaper: as its name shows.
Structure:
there are two structures for this pattern:
  • Class adapter: this is implemented by letting the adapter inherit both both the target and the adaptee. I am not so into this stucture while the C# doesnot support the multiple inheritance.
  • Object adapter: this is implemented by letting the adapter inherit the target but have a reference of adaptee. Personally speaking i like this structure 

A small code designed(C#) is to demonstrate this pattern(Object adapter):

namespace Adapter
{
public class Target
{
public virtual void DoSomethingForTarget()
{
//do something here
}
}


public class Adaptee
{
public void DoSomethingForAdaptee()
{
//do something here
}
}

public class Adapter:Target
{
private Adaptee adaptee = new Adaptee();//got a reference of adaptee

public override void DoSomethingForTarget()
{
adaptee.DoSomethingForAdaptee();//here adapt the adaptee to the target exactly
}
}

public class Client
{
static void Main(string[] args)
{
Target myTarget = new Adapter();

myTarget.DoSomethingForTarget();
}
}
}

this pattern is simple but i did not ever use it in the real project. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值