zoukankan      html  css  js  c++  java
  • 设计模式之(二)Adapter模式

    今天学习Adapter模式,An adapter helps two incompatible interfaces to work together. This is the real world definition for an adapter. Adapter design pattern is used when you want two different classes with incompatible interfaces to work together. The name says it all. Interfaces may be incompatible but the inner functionality should suit the need. The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.

    现在通过例子说明:

    假设有2个类 Play和Walk

    public class Play {
    public void playPhone() {
    System.out.println("play iphone");
    }
    }

    public class Walk {
    public void walk() {
    System.out.println("I walk on the street");
    }
    }

    现在需要一个适配器,使一个人一边走路一边玩手机

    可以使得适配器继承其中一个类,然后将另一个类作为该适配器类的成员变量。

    public class WalkAdapter {
    private Play play;
    public WalkAdapter(Play play) {
    this.play = play;
    }
    public void play() {
    return play.playPhone();
    }
    }


    还可以采用多继承,但是Java没有多继承,只能通过接口实现。设置两个接口,分别让两个类实现接口。

    public interface IPlay {
    public void playPhone();
    }
    public interface IWalk {
    public void walk();
    }

    public class Play implements IPlay{
    @Override
    public void playPhone() {
    System.out.println("play iphone");
    }
    }


    public class Walk implements IWalk{
    @Override
    public void walk() {
    System.out.println("I walk on the street");
    }
    }

    然后让Adapter实现2个接口,同时让2个类的对象作为Adapter的成员变量。

    public class Adapter implements IWalk, IPlay {
    private Play play;
    private Walk walk;
    public Adapter(Play play, Walk walk) {
    this.play = play;
    this.walk = walk;
    }
    public void play() {
    return play.playPhone();
    }
    public void walk() {
    return walk.walk();
    }
    }


  • 相关阅读:
    Oracle PL/SQL中如何使用%TYPE和%ROWTYPE
    SVN使用教程总结
    实践SQLServer Tuning
    SQL性能优化:如何定位网络性能问题
    windows7下修改hosts文件无效解决办法
    jQuery Event.stopPropagation() 函数详解
    引用js或css后加?v= 版本号的用法
    JS实现点击跳转登陆邮箱
    DWZ (JUI) 教程 navTab 刷新分析
    CPU与内存的关系
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3343543.html
Copyright © 2011-2022 走看看