设计模式——适配器模式(本质:转换匹配,复用功能)

一、定义:

       将一个类的接口转换成客户希望的另外的一个接口。Adapte模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

二、分类:

1、对象适配器:松耦合

UML图:

 

 

 

2、类适配器:高耦合

 

 

三、组成:

1、目标角色:Target客户所期待的接口

2、适配器角色:Adapter:内部包装一个Adaptee对象,将源接口转换为目标接口。

3、源角色:Adaptee

 

四、示意代码:

public class Adaptee {
	public void specialRequest() {
		System.out.println("this is a special request!");
	}
}

public class Adapter extends Target {
	Adaptee adaptee=new Adaptee();
	
	@Override
	public void request() {
		this.adaptee.specialRequest();

	}

}


public  abstract class Target {
	public void request(){
		System.out.println("this is a normal request!");
	}
}


public class Client {

	public static void main(String[] args) {
		Target t=new Adapter();
		t.request();

	}

}

 

五、优缺点:

优点:

          更好的复用性

          更好的可扩展性

                 在实现适配器功能的时候,可以调用自己开发的功能,从而自然地扩展系统的功能

缺点:

          过多地使用适配器,会让系统非常凌乱,不容易整体进行把握。

 

六、课本例子:姚明NBA打篮球:

1、UML图:

 

2、代码实现:

 

//目标角色

public abstract class Player {
	protected String name=null;
	public Player(String name) {
		this.name=name;
	}
	public void defense() {
		System.out.println(name+"denfense");
	}
	public void attack() {
		System.out.println(name+"attack");
	}
	

}
//具体,,,

public class Guards extends Player {

	public Guards(String name) {
		super(name);
	}

}


public class Center extends Player {

	public Center(String name) {
		super(name);
		
	}

}

//适配器角色
public class Translate extends Player{

	ForeignCenter yaoMing=null;
	public Translate(String name) {
		super(name);
		yaoMing=new ForeignCenter(name);
	}
	
	public void attack() {
		yaoMing.进攻();//调用外籍球员的中文方法
	}
	public void defense() {
		yaoMing.防守();
	}

}

//源角色
public class ForeignCenter {
	private String name=null;
	public ForeignCenter(String name) {
		this.name=name;
	}
	public void 进攻() {            //-----------外籍球员只能听懂中文
		System.out.println(name+"进攻");
	}
	public void 防守() {
		System.out.println(name+"防守");
	}

}

//场景类
public class Client {

	public static void main(String[] args) {
		Player p=new Translate("姚明");
		
		p.attack();
		p.defense();
		
		
		p=new Guards("麦克格雷迪");
		p.attack();
		p.defense();
		

	}

}

 

 

The end;

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值