java设计模式代码-适配器模式

2023-07-09

类适配器模式

目标类

public class Demo {
    public void demo(){
        System.out.println("目标方法");
    }
}

目标接口


public interface Target {
    /**
     * 目标方法
     */
    void targetMethod();
}


适配器类


public class Adapter extends Demo implements Target{
    @Override
    public void targetMethod() {
        System.out.println("适配器方法");
        demo();
    }
}

测试类

public class App {
    public static void main(String[] args) {
        //外观模式
        Adapter adapter = new Adapter();
        adapter.targetMethod();
    }
}

输出结果

适配器方法
目标方法

对象适配器模式

目标类

public class Demo {
    public void demo(){
        System.out.println("目标方法");
    }
}

目标接口


public interface Target {
    /**
     * 目标方法
     */
    void targetMethod();
}


适配器类


public class Adapter implements Target{
    private Demo demo = new Demo();

    @Override
    public void targetMethod() {
        System.out.println("适配器方法");
        demo.demo();
    }
}

测试类

public class App {
    public static void main(String[] args) {
        //外观模式
        Adapter adapter = new Adapter();
        adapter.targetMethod();
    }
}

输出结果

适配器方法
目标方法