结构型模式1:
适配器(变压器)模式:把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口原因不匹配而无法一起工作的两个类能够一起工作。适配类可以根据参数返还一个合适的实例给客户端。
追MM比喻:ADAPTER―在朋友聚会上碰到了一个美女Sarah,从香港来的,可我不会说粤语,她不会说普通话,只好于我的朋友kent了,他作为我和Sarah之间的Adapter,让我和Sarah可以相互交谈了(也不知道他会不会耍我)
适配器模式的使用情况:
• 你想使用一个已经存在的类,而它的接口不符合你的需求。
• 你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作。
• (仅适用于对象Adapter)你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口。对象适配器可以适配它的父类接口。
类适配器
对象适配器
- package com.visionsky.DesignPattern;
- interface Target {
- void Request();
- }
- class Adaptee {
- void SpecificRequst() {
- System.out.println("Adaptee's SpecificRequst");
- }
- }
- class Adapter extends Adaptee implements Target
- {
- @Override
- public void Request() {
- System.out.println("Adapter's Request");
- super.SpecificRequst();
- }
- }
- public class AdapterDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Target t=new Adapter();
- t.Request();
- }
- }
对象适配器:
- package com.visionsky.DesignPattern;
- interface Target {
- void Request();
- }
- class Adaptee {
- void SpecificRequst() {
- System.out.println("Adaptee's SpecificRequst");
- }
- }
- class Adapter implements Target
- {
- private Adaptee adaptee;
- public Adapter()
- {
- this.adaptee=new Adaptee();
- }
- @Override
- public void Request() {
- System.out.println("Adapter's Request");
- adaptee.SpecificRequst();
- }
- }
- public class AdapterDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Target t=new Adapter();
- t.Request();
- }
- }