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


  • 相关阅读:
    创建类型5-3:单例模式(Singleton Pattern)
    创建类型5-2:抽象工厂模式(Abstract Factory Pattern)
    创建类型5-1:工厂模式(Factory Pattern)
    第一章:Netty介绍
    第二章:第一个Netty程序
    第四章:Transports(传输)
    第十六章:从EventLoop取消注册和重新注册
    第十五章:选择正确的线程模型
    第十四章:实现自定义的编码解码器
    第十三章:通过UDP广播事件
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3343543.html
Copyright © 2011-2022 走看看