设计模式之适配器模式

it2022-05-05  163

Adapter模式也叫适配器模式,是构造型模式之一,通过Adapter模式可以改变已有类(或外部类)的接口形式。

适配器模式有两种实现方式

(一)通过继承实现Adapter

例子:电流降压

电流类Current:

1 package com.Design.Adapter; 2 3 public class Current { 4 5 public void user220V(){ 6 System.out.println("使用220V电流"); 7 } 8 9 } View Code

降压后的适配器类(继承):

1 package com.Design.Adapter; 2 3 public class Adapter extends Current{ 4 5 public void use18V() { 6 System.out.println("使用适配器"); 7 this.user220V(); 8 } 9 10 11 } View Code

上述就是,通过继承来实现的适配器模式,调用的方法还是老方法。

(二)通过委让实现Adapter(就是适配器持有原来的类的引用)

例子:

就是将上述的继承改成持有引用:

1 package com.Design.Adapter; 2 3 public class Adapter2 { 4 5 private Current current; 6 7 public Adapter2(Current current){ 8 this.current = current; 9 } 10 11 public void user18V() { 12 System.out.println("使用适配器"); 13 this.current.user220V(); 14 } 15 16 17 } View Code

两种方式都比较容易理解。

 

转载于:https://www.cnblogs.com/huaxueyihao/p/8798817.html

相关资源:各显卡算力对照表!

最新回复(0)