dp_AdapterPattern

适配器模式 Adapter Pattern 变压器模式

Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

将一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。适配器模式就是一个接口或类转换成其他的接口或类,适配器相当于一个包装器。

目标角色(Target):该角色定义要转换成的目标接口。

package com.DesignPattern.Structural.Adapter;

public interface Target {
    public void request();
}

源角色(Adaptee):需要被转换成目标角色的源角色。

package com.DesignPattern.Structural.Adapter;

//源角色
public class Adaptee {
    // 原有业务处理
    public void specificRequest() {
        System.out.println("原有业务处理");
    }
}

适配器角色(Adapter):该角色是适配器模式的核心,其职责是通过继承或是类关系的方式,将源角色转换为目标角色。

package com.DesignPattern.Structural.Adapter;

public class Adapter extends Adaptee implements Target {
    @Override
    public void request() {
        super.specificRequest();
    }
}
package com.DesignPattern.Structural.Adapter;

public class Client {

    public static void main(String[] args){
        //适配器模式应用
        Target target=new Adapter();
        target.request();
    }
}

适配器模式的实例

Dumplings.java

package com.DesignPattern.Structural.Adapter;

public class Dumplings {

    public void makeDumplings(){
        System.out.println("调馅");
        System.out.println("擀皮");
        System.out.println("包馅");
    }
}

Hundun.java

package com.DesignPattern.Structural.Adapter;

public interface Hundun {
    public void makeHundun();
}

FoodAdapter.java

package com.DesignPattern.Structural.Adapter;

public class FoodAdapter extends Dumplings implements Hundun {
    @Override
    public void makeHundun() {
        super.makeDumplings();
        System.out.println("混沌和水饺一样都是用面包馅的食品");
    }
}

ClientDemo.java

package com.DesignPattern.Structural.Adapter;

public class ClientDemo {

    public static void main(String[] args){
        Hundun h=new FoodAdapter();
        h.makeHundun();
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载|Copyright ©2011-2015,Supernatural, All Rights Reserved.

时间: 2024-08-25 22:58:48

dp_AdapterPattern的相关文章