• 适配器模式


    1、简介

    适配器(Adapater Pattern)作为二个不兼容接口的桥梁。
    例如:内存卡 -> 读卡器 -> 电脑硬盘

    简单来说,就是将一个类的接口转换为客户希望的另一个接口,使得原本因为接口不兼容的那些类可以一起工作。

    关键思想: 继承或者依赖已有的对象,实现想要的目标接口

    2、使用

    // 高级播放器接口
    public interface AdvenceMediaPlayer {
    	
    	void playMp4(String fileName);
    	
    	void playMp5(String fileName);
    }
    // 普通播放器接口
    public interface MediaPlayer {
    
    	void play(String audioType, String fileName);
    }
    
    // 适配器类
    public class MediaAdapter implements MediaPlayer{
    
    	private AdvenceMediaPlayer advenceMediaPlayer;
    	
    	public MediaAdapter(String audioType) {
    		if(audioType.equalsIgnoreCase("mp4")) {
    			advenceMediaPlayer = new Mp4Player();
    		}else if(audioType.equalsIgnoreCase("mp5")) {
    			advenceMediaPlayer = new Mp5Player();
    		}
    	}
    		
    	@Override
    	public void play(String audioType, String fileName) {
    		if(audioType.equalsIgnoreCase("mp4")) {
    			advenceMediaPlayer.playMp4(fileName);
    		}else if(audioType.equalsIgnoreCase("mp5")) {
    			advenceMediaPlayer.playMp5(fileName);
    		}
    	}
    }
    // mp4
    public class Mp4Player implements AdvenceMediaPlayer{
    
    	@Override
    	public void playMp4(String fileName) {
    		System.out.println("Mp4 player play "+fileName);
    	}
    	
    	@Override
    	public void playMp5(String fileName) {
    		
    	}
    }
    // mp5
    public class Mp5Player implements AdvenceMediaPlayer{
    
    	@Override
    	public void playMp4(String fileName) {
    		
    	}
    	
    	@Override
    	public void playMp5(String fileName) {
    		System.out.println("Mp5 player play "+fileName);
    	}
    }
    // mp3
    public class AudioPlayer implements MediaPlayer{
    
    	private MediaAdapter adapter;
    	
    	@Override
    	public void play(String audioType, String fileName) {
    		if(audioType.equalsIgnoreCase("mp3")) {
    			System.out.println("mp3 play "+fileName);
    		}else if(audioType.equalsIgnoreCase("mp4")
    				|| audioType.equalsIgnoreCase("mp5")) {
    			adapter = new MediaAdapter(audioType);
    			adapter.play(audioType, fileName);
    		}else {
    			System.out.println("Invalid mediatype"+audioType+" not support!");
    		}
    	}
    }
    // 测试
    /* 适配器模式 */
    		AudioPlayer player = new AudioPlayer();
    		player.play("mp3", "空");
    		player.play("mp4", "空");
    		player.play("mp5", "空");
    		player.play("mp6", "空");
    
  • 相关阅读:
    如何应对“需求不确定型项目”?
    Python virtualenv安装库报错SSL: CERTIFICATE_VERIFY_FAILED
    R语言之——字符串处理函数
    你看那个人他像一条狗
    BZOJ 3744: Gty的妹子序列 [分块]
    BZOJ 3731 3731: Gty的超级妹子树 [树上size分块 !]
    BZOJ 3720: Gty的妹子树 [树上size分块]
    BZOJ 4129: Haruna’s Breakfast [树上莫队 分块]
    SPOJ COT2 Count on a tree II [树上莫队]
    【WC2013】糖果公园 [树上莫队]
  • 原文地址:https://www.cnblogs.com/kungFuPander/p/13474571.html
Copyright © 2020-2023  润新知