適配器模式是鏈接兩個不兼容接口的橋樑,主要分爲三種:類適配器、對象適配器以及接口適配器,本文根據https://blog.csdn.net/u012359453/article/details/79165080所給的例子使用matlab語言對三種適配器進行實現。測試
已有的接口和類(AC220V):.net
IAC220V.m對象
classdef IAC220V < handle methods(Abstract) getAC220V(~); end end
AC220V.mblog
classdef AC220V < IAC220V properties isAC = true; voltage = 220; end methods function obj = AC220V(voltage,isAC) obj.isAC = isAC; obj.voltage = voltage; end function [voltage,isAC] = getAC220V(obj) voltage = obj.voltage; isAC = obj.isAC; end end end
目標接口:(DC5V,注意二者的方法簽名是不一樣的)接口
classdef IDC5V < handle methods(Abstract) getDC5V(~); end end
類適配器(將AC220V轉化成DC5V):get
classdef ClassAdapter < AC220V & IDC5V methods function obj = ClassAdapter(voltage,isAC) obj = obj@AC220V(voltage,isAC); end function [new_voltage,new_isAC] = getDC5V(obj) [voltage,isAC] = obj.getAC220V(); new_voltage = 0; new_isAC = false; if(isAC) new_voltage = voltage / 44; new_isAC = false; end end end end
對象適配器:io
classdef ObjAdapter < IDC5V properties pAC220 end methods function obj = ObjAdapter(pAC220) if(metaclass(pAC220) <= ?IAC220V) obj.pAC220 = pAC220; end end function [new_voltage,new_isAC] = getDC5V(obj) new_voltage = 0; new_isAC = false; if(~isempty(obj.pAC220)) [voltage,isAC] = obj.pAC220.getAC220V(); if(isAC) new_voltage = voltage / 44; new_isAC = false; end end end end end
接口適配器:function
IDCOutput.m (定義通用輸出接口)class
classdef IDCOutput < handle methods(Abstract) getDC5V(~); getDC12V(~); end end
IAdapter.m(定義默認適配器接口)meta
classdef IAdapter < IDCOutput properties power end methods function obj = IAdapter(power) obj.power = power; end function [voltage,isAC] = getDC5V(~) voltage = 0; isAC = false; end function [voltage,isAC] = getDC12V(~) voltage = 0; isAC = false; end end end
AC220VAdapter.m (定義具體適配器方法,AC220V輸入爲例)
classdef AC220VAdapter < IAdapter methods function obj = AC220VAdapter(pAC220V) obj = obj@IAdapter(pAC220V); end function [new_voltage,new_isAC] = getDC5V(obj) new_voltage = 0; new_isAC = false; if(~isempty(obj.power)) [voltage,isAC] = obj.power.getAC220V(); if(isAC) new_voltage = voltage / 44; new_isAC = false; end end end end end
測試代碼
a = ClassAdapter(220,true); disp(a.getDC5V()); b = ObjAdapter(AC220V(223,true)); disp(b.getDC5V()); c = AC220VAdapter(AC220V(221,true)); disp(c.getDC5V())