设计模式——适配器模式

适配器模式:将一个类的接口,转换成客户期望的另一个接口,适配器让原本接口不兼容的类可以合作无间。

1.对象适配器

package main

import "fmt"

//标准接口
type Target interface {
	quack()
	fly()
}

//被适配对象
type Adaptee interface{
	gobble()
	fly()
}

//适配器
type Adapter struct{
	Adaptee
}
func NewAdapter(t Adaptee) Adapter{
	return Adapter{Adaptee:t}
}
func (t Adapter) quack(){
	t.Adaptee.gobble()
}
func (t Adapter) fly(){
	for i:=0;i<5;i++ {//鸭子比火鸡飞得远
		t.Adaptee.fly()
	}
}

//待适配的火鸡对象
type AdapteeObject struct{
}
func (a AdapteeObject) gobble(){
	fmt.Println("ge ge da ……")
}
func (a AdapteeObject) fly(){
	fmt.Println("fly")
}

func main() {
	turkey  := AdapteeObject{}
	adapter := NewAdapter(turkey)
	adapter.quack()
	adapter.fly()
}

2.类适配器(采用继承:适配器类继承目标类和待适配类)

//JAVA中类适配器的实现:
// 适配器类,继承了被适配类,同时实现标准接口
class Adapter extends Adaptee implements Target{
	public void request() {
		super.specificRequest();
	}
}

// 在主函数中使用适配类
Target adapter = new Adapter();
adapter.request();

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值