设计模式6-适配器模式

引用: 

1. 适配器模式 — Graphic Design Patterns

适配器模式(Adapter Pattern) :将一个接口转换成客户希望的另一个接口,适配器模式使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。

适配器模式包含如下角色:

  • Target:目标抽象类
  • Adapter:适配器类
  • Adaptee:适配者类
  • Client:客户类

适配器模式有对象适配器和类适配器两种实现:

../_images/Proxy.jpg

../_images/Adapter.jpg

一、go语言版

package main
import "fmt"
type Target interface {
    Request() 
}
type Adaptee struct{}
func (*Adaptee) RealRequest() {
    fmt.Printf("real Request\n")
}
type Adapter struct {
    adaptee *Adaptee
}
func (adapter* Adapter) Request() {
    adapter.adaptee.RealRequest()
}
func NewAdapter(a *Adaptee) Target {
    return &Adapter {
        adaptee : a,
    }
}
func main() {
    adaptee := new(Adaptee)
    fmt.Printf("adaptee type = %T\n",adaptee)
    target := NewAdapter(adaptee)
    target.Request()
}

二、c++语言版

#include <iostream>
using namespace std;
class Target
{
public: 
    virtual void Request() {
        cout << "target request" << endl;
    }
};
class Apaptee
{
public:
    void RealRequest() {
        cout << "real request" << endl;
    }
};
class Adapter:public Target,private Apaptee
{
    virtual void Request() {
        cout << "adapter request" << endl;
        this->RealRequest();
    }
};
int main()
{
    Target *target = new Adapter();
    target->Request();
    return 0;
}

三、c语言版

#include <stdio.h>
#include <stdlib.h>
typedef struct _Adaptee {
    void (*RealRequest)(struct _Adaptee *pAdaptee);
}Adaptee;
typedef struct _Adapter {
    Adaptee *pAdaptee;
    void (*Request)(struct _Adapter *pAdaptee);
}Adapter;
void RealRequest(struct _Adaptee *pAdaptee)
{
    printf("RealRequest\n");
}
void Request(struct _Adapter *pAdaptee)
{
    printf("Request\n");
    pAdaptee->pAdaptee->RealRequest(pAdaptee->pAdaptee);
}
int main()
{
    Adapter *pAdapter = (Adapter *)malloc(sizeof(Adapter));
    Adaptee *pAdaptee = (Adaptee *)malloc(sizeof(Adaptee));
    pAdaptee->RealRequest = RealRequest;
    pAdapter->Request = Request;
    pAdapter->pAdaptee = pAdaptee;
    pAdapter->Request(pAdapter);
    return 0;    
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值