您的位置:首页 > 其它

适配器设计模式简单实现

2017-08-16 09:24 246 查看
1、适配器设计模式场景

当前类不能满足客户端需求,但又不能修改当前类(开闭原则),因此创建【适配器类】和【客户端目标接口】,实现方式有两种:1)适配器类【继承】当前类并实现目标接口;2)适配器类包含当前类引用并实现目标接口

2、代码实现

/**
* 现有类
* @author Administrator
*
*/
public class Adaptee
{
public void method1(){
System.out.println("---method1---");
}
}


/**
* 客户端需求接口,大于现有类
* @author Administrator
*
*/
public interface TargetInterface
{
public void method1();
public void method2();
}


/**
* 适配器实现方法1:继承当前类并实现目标接口
* @author Administrator
*
*/
public class Adapter1 extends Adaptee implements TargetInterface
{
@Override
public void method2()
{
System.out.println("---method2----");
}
}


/**
* 适配器实现2:持有当前类引用并实现目标接口
* @author Administrator
*
*/
public class Adapter2 implements TargetInterface
{
private Adaptee adaptee = new Adaptee();

@Override
public void method1()
{
adaptee.method1();
}

@Override
public void method2()
{
System.out.println("---method2---");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式