设计模式——Adapter模式(变压器)
变压器模式使原本无法在一起工作的两个类能够在一起工作。
在以下各种情况下使用变压器模式:
第一、 你需要使用现有的类,而此类的接口不符合你的需要。
第二、 你想要建立一个可以重复使用的类,用以与一些彼此之间没有太大关联的一些类, 包括一些可能在将来引进的类一起工作。这些源类不一定有很复杂的接口。
第三、 (对实例形式的变压器模式而言)你需要改变多个已有的子类的接口, 如果使用类形式的变压器模式,就要针对每一个子类做一个变压器类,而这不太实际。
• 目标(Target)。这就是我们所期待得到的接口。注意,由于这里讨论的是类变压器模式,因此目标不可以是类。
• 源(Adaptee)。现有需要适配的接口。
• 变压器(Adapter)。变压器类是本模式的核心。变压器把源接口转换成目标接口。显然,这一角色不可以是接口, 而必须是实类。
1 package com.javapatterns.adapter; 2 interface Target 3 { 4 /** 5 * Class Adaptee contains operation sampleOperation1. 6 */ 7 void sampleOperation1(); 8 /** 9 * Class Adaptee doesn't contain operation sampleOperation2. 10 */ 11 void sampleOperation2(); 12 } 13 class Adaptee 14 { 15 public void sampleOperation1() 16 { 17 System.out.println("Class Source s1"); 18 } 19 } 20 class Adapter extends Adaptee implements Target 21 { 22 /** 23 * Class Adaptee doesn't contain operation sampleOperation2. 24 */ 25 public void sampleOperation2() 26 { 27 System.out.println("Class Adapter s2"); 28 } 29 } 30 public class classAdapter{ 31 public static void main(String[] args){ 32 Adapter adapter = new Adapter(); 33 adapter.sampleOperation2(); 34 } 35 }