Java设计模式——适配器模式

适配器模式分为两种:类适配器模式和对象适配器模式。废话不多说,直接上代码。

1、类适配器模式

public interface TargetInterface {
    void method1();

    void method2();
}

/**
 * 需要被适配的类,该类要实现TargetInterface接口,但是不能被修改。
 *
 */
class Adaptee {
    public void method1() {
        System.out.println("method1");
    }
}

/**
 * 适配器类
 *
 */
class Adapter extends Adaptee implements TargetInterface {
    public void method2() {
        System.out.println("method2");
    }
}

public class AdapterTest {
    public static void main(String[] args) {
        Adapter adapt = new Adapter();
        adapt.method1();
        adapt.method2();
    }
}

2、对象适配器模式

public interface TargetInterface {
    void method1();

    void method2();
}

/**
 * 需要被适配的类,该类要实现TargetInterface接口,但是不能被修改。
 *
 */
class Adaptee{
    public void method1(){
        System.out.println("method1");
    }
}

/**
 * 适配器类
 *
 */
class Adapter implements TargetInterface {
    private Adaptee adaptee;

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

    public void method1() {
        this.adaptee.method1();
    }

    public void method2() {
        System.out.println("method2");
    }
}

public class AdapterTest {
    public static void main(String[] args) {
        Adapter adapt = new Adapter(new Adaptee());
        adapt.method1();
        adapt.method2();
    }
}

 

转载于:https://www.cnblogs.com/zengxiaoliang/p/8074949.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值