引用:
1. 适配器模式 — Graphic Design Patterns
适配器模式(Adapter Pattern) :将一个接口转换成客户希望的另一个接口,适配器模式使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。
适配器模式包含如下角色:
- Target:目标抽象类
- Adapter:适配器类
- Adaptee:适配者类
- Client:客户类
适配器模式有对象适配器和类适配器两种实现:
一、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;
}