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

适配器模式:将一个类的接口转换为客户需要的目标接口

一、类适配器模式

    这个用变压器的列子再好不过了,大话设计模式--(朋友从美国带回个微波炉,美国电压110V,中国电压220V,幸好朋友有先见知名,带了个变压器);

    现在我们来模拟一下:

/** 原角色、当前可使用220v*/  

public class Adaptee {
    public void provide220V(){
        System.out.println("220V 电压开始工作");
    }
}

/** 目标角色 */

public interface Target {
    public void provide220V();
    public void provide110V();
}

/**适配器角色*/

public Adapter extends Adatee implements Target{

        @Override
    public void provide110V() {
        System.out.println("110V 电压开始工作");
    }

}

/** 客户端用列*/

public class Client {
    public static void main(String[] args) {
        Target adapter = new Adapter();/*适配器*/
        adapter.provide110V();
        adapter.provide220V();
    }
}

二、对象适配器模式(有一个插座,这个插座是三个口的,但是我们手上只有两个触角的插头,方法就是找一个转换头来)

/**原角色*/
/**
 * 二孔插板
 */
public interface TwoSpile {
  void workTwo();
}

public class Adaptee implements TwoSpile {

    @Override
    public void workTwo() {
        // TODO Auto-generated method stub
        System.out.println("二孔插座工作。。。");
    }

}

/**目标角色**/

/**
 * 三孔插板
 */
public interface Target {
    public void workThree();
    public void workTwo();
}

/**适配器*/

public class Adapter implements Target {
    private TwoSpile twoSpile; 
    
    
    public Adapter(TwoSpile twoSpile) {
        this.twoSpile = twoSpile;
    }

    public TwoSpile getTwoSpile() {
        return twoSpile;
    }

    public void setTwoSpile(TwoSpile twoSpile) {
        this.twoSpile = twoSpile;
    }

    @Override
    public void workThree() {
        // TODO Auto-generated method stub
        System.out.println("三孔插座工作....");
    }

    @Override
    public void workTwo() {
        this.twoSpile.workTwo();
    }
    /**测试用例*/

public class Client {
    public static void main(String[] args) {
        TwoSpile twoSpile = new Adaptee();
        Target threeSpile = new Adapter(twoSpile);
        threeSpile.workThree();
        threeSpile.workTwo();
    }
}

 

 

        

转载于:https://my.oschina.net/u/3190930/blog/897779

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值