適配器模式
將某個類的接口轉(zhuǎn)換成客戶端期望的另一個接口表示。使得原本由于接口不兼容而不能一起工作的那些類能在一起工作。
類適配器
/**
* @USER: lynn
* @DATE: 2020/4/26
**/
public class 類適配器 {
public static void main(String[] args) {
充電器 phone = new 手機(jī)();
System.out.println(phone.高壓轉(zhuǎn)低壓());
}
}
class 高壓電{
public int 插座(){
int output = 220;
return output;
}
}
interface 充電器{
int 高壓轉(zhuǎn)低壓();
}
class 手機(jī) extends 高壓電 implements 充電器{
@Override
public int 高壓轉(zhuǎn)低壓() {
int 高壓電 = 插座();
//適配細(xì)節(jié)
int 低壓電 = 高壓電/44;
return 低壓電;
}
}
或者
/**
* @USER: lynn
* @DATE: 2020/4/26
**/
public class 類適配器 {
public static void main(String[] args) {
充電器 phone = new 手機(jī)();
System.out.println(phone.高壓轉(zhuǎn)低壓());
}
}
abstract class 高壓電 implements 充電器{
public int 插座(){
int output = 220;
return output;
}
}
interface 充電器{
int 高壓轉(zhuǎn)低壓();
}
class 手機(jī) extends 高壓電{
@Override
public int 高壓轉(zhuǎn)低壓() {
int 高壓電 = 插座();
//適配細(xì)節(jié)
int 低壓電 = 高壓電/44;
return 低壓電;
}
}
對象適配器
對象適配器擁有源角色的實(shí)例
/**
* @USER: lynn
* @DATE: 2020/4/26
**/
public class 對象適配器 {
public static void main(String[] args) {
充電器 phone = new 手機(jī)對象(new 高壓電());
System.out.println(phone.高壓轉(zhuǎn)低壓());
}
}
class 手機(jī)對象 extends 高壓電 implements 充電器{
private 高壓電 伏220高壓電;
public 手機(jī)對象(高壓電 伏220高壓電) {
this.伏220高壓電 = 伏220高壓電;
}
@Override
public int 高壓轉(zhuǎn)低壓() {
int 高壓電 = 伏220高壓電.插座();
//適配細(xì)節(jié)
int 低壓電 = 高壓電/44;
return 低壓電;
}
}
接口適配器
通過抽象類來實(shí)現(xiàn)適配
/**
* @USER: lynn
* @DATE: 2020/4/26
**/
public class 接口適配器 {
public static void main(String[] args) {
手機(jī)輸入 phone = new 手機(jī)適配器(new 工業(yè)插座());
System.out.println("輸出后電壓"+phone.輸入電壓());
phone = new 手機(jī)適配器(new 家庭插座());
System.out.println("輸出后電壓"+phone.輸入電壓());
}
}
abstract class 插座{
public int 輸出電壓(){
return 200;
}
}
class 家庭插座 extends 插座{
@Override
public int 輸出電壓() {
return 220;
}
}
class 工業(yè)插座 extends 插座{
@Override
public int 輸出電壓() {
return 440;
}
}
interface 手機(jī)輸入{
int 輸入電壓();
}
class 手機(jī)適配器 implements 手機(jī)輸入{
private 插座 chazuo;
public 手機(jī)適配器(家庭插座 jiatingchazuo) {
this.chazuo = jiatingchazuo;
}
public 手機(jī)適配器(工業(yè)插座 gongyechazuo) {
this.chazuo = gongyechazuo;
}
@Override
public int 輸入電壓() {
if (chazuo !=null){
System.out.println("輸出前電壓:"+chazuo.輸出電壓());
}
//適配邏輯
return 5;
}
}
- 使用場景
- 項(xiàng)目接口的新需求熏兄,不用更改老代碼,實(shí)現(xiàn)代碼兼容