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();
    }
    }


  • 相关阅读:
    音频处理入门笔记
    python对象-多态
    python对象的不同参数集合
    python多重继承的钻石问题
    python对象的多重继承
    python类继承的重写和super
    Python继承扩展内置类
    python对象继承
    Python模块与包
    Pyhton对象解释
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3343543.html
Copyright © 2011-2022 走看看