适配器模式

1. 什么时候要使用适配器模式?

        在软件系统中,由于应用环境的变化,常常需要将一些现存的对象放在新的环境中使用,但是新的环境要求的接口是这些现存环境所不满足的。那么如何应对这种迁移的变化呢?此时就要用到适配器模式。

 

2. 什么是适配器模式?

        适配器模式的类图(对象适配):

3. 类适配器模式

package 类适配器模式;

//用户期待的接口
interface Target {
	void MyOutput();
}

//原有接口
interface Adaptee {
	void Output();
}

//实现类1
class ConcreteAdaptee implements Adaptee {
	public void Output() {
		System.out.println("From ConcreteAdaptee");
	}
}

//实现类2
class ConcreteAdaptee2 implements Adaptee {
	public void Output() {
		System.out.println("From ConcreteAdaptee2");
	}
}

//实现类1的适配器
class ConcreteAdapter extends ConcreteAdaptee implements Target {
	public void MyOutput() // 适配
	{
		this.Output();
	}
}

//实现类2的适配器
class ConcreteAdapter2 extends ConcreteAdaptee2 implements Target {
	public void MyOutput() {
		this.Output();
	}
}

public class Client {

	public static void main(String[] args) {
		Target target = new ConcreteAdapter();
		target.MyOutput();

		Target target2 = new ConcreteAdapter2();
		target2.MyOutput();
	}
}

不足就是对多个实现类要定义多个适配器

 

4. 对象适配器模式

package 对象适配器模式;

//用户期待的接口
interface Target {
	void MyOutput();
}

//原有接口
interface Adaptee {
	void Output();
}

//实现类1
class ConcreteAdaptee implements Adaptee {
	public void Output() {
		System.out.println("From ConcreteAdaptee");
	}
}

//实现类2
class ConcreteAdaptee2 implements Adaptee {
	public void Output() {
		System.out.println("From ConcreteAdaptee2");
	}
}

//适配器  而且适配器可以适配多个接口
class Adapter implements Target
{
    private Adaptee adaptee; // 必须要维护一个Adaptee类型的成员变量

    public Adapter(Adaptee adaptee)
    {
        this.adaptee = adaptee;
    }

    public void MyOutput()
    {
        this.adaptee.Output();
    }
}

public class Client {

	public static void main(String[] args) {
		//原来的接口 通过适配器 就成为现在用户需要的接口
		Target target = new Adapter(new ConcreteAdaptee());
        target.MyOutput();

        target = new Adapter(new ConcreteAdaptee2());
        target.MyOutput();
	}
}

5. .Net中的适配器模式



 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值