结构模式-适配器模式

适配器模式:把一个类的接口变换成客户端所期待的另一种接口,从而使本因接口不匹配而无法在一起工作的两个类能够在一起工作。

适配器模式有类的适配器模式和对象的适配器模式两种:

下面先来看类的适配器模式

源:

package com.javapatterns.adapter.classAdapter;

public class Adaptee {
    public void sampleOperation1(){}
}

 目标:

package com.javapatterns.adapter.classAdapter;

public interface Target {
    /**
     * Class Adaptee contains operation sampleOperation1. 
     */
    void sampleOperation1();

    /**
     * Class Adaptee doesn't contain operation sampleOperation2. 
     */
    void sampleOperation2();
}

 

适配器

package com.javapatterns.adapter.classAdapter;

public class Adapter extends Adaptee implements Target {
    /**
     * Class Adaptee doesn't contain operation sampleOperation2. 
     */
    public void sampleOperation2(){
        // Write your code here
    }
}

 

 客户端

package com.javapatterns.adapter.classAdapter;

public class Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Adapter adapter = new Adapter();
		adapter.sampleOperation1();
		adapter.sampleOperation2();
	}

}

 

 

对象的适配器

源:

package com.javapatterns.adapter.objectAdapter;

public class Adaptee {
    public void sampleOperation1(){}
}

 

目标:

package com.javapatterns.adapter.objectAdapter;

public interface Target {
    /**
     * Class Adaptee contains operation sampleOperation1. 
     */
    void sampleOperation1();

    /**
     * Class Adaptee doesn't contain operation sampleOperation2. 
     */
    void sampleOperation2();
}

 

适配器:

package com.javapatterns.adapter.objectAdapter;

public class Adapter implements Target {

	private Adaptee adaptee;

	public Adapter(Adaptee adaptee) {
		super();
		this.adaptee = adaptee;
	}

	public void sampleOperation1() {
		adaptee.sampleOperation1();
	}

	public void sampleOperation2() {
		// Write your code here
	}
}

 客户端

package com.javapatterns.adapter.objectAdapter;

public class Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Adapter adapter = new Adapter(new Adaptee());
		adapter.sampleOperation1();
		adapter.sampleOperation2();
	}

}

 

你可能感兴趣的:(工作)