适配器模式的三种方式

第一种方式(基于继承):
package com.unis.zzg.adapter;
public interface Target {
	
	void method1();

}

package com.unis.zzg.adapter;

public class Adaptee {
	
	public void method2(){
		System.out.println("目标方法");
	}

}

package com.unis.zzg.adapter;

public class Adpater extends Adaptee implements Target {

	@Override
	public void method1() {
		this.method2();
	}

}


2.第二种方式(基于组合的方式)
package com.unis.zzg.adapter1;

public interface Target {
	
	void method1();

}

package com.unis.zzg.adapter1;

public class Adpatee {
	
	public void method2(){
		System.out.println("目标函数");
	}

}

package com.unis.zzg.adapter1;

public class Adapter implements Target {
	
	private Adpatee adpatee;
	
	public Adapter(Adpatee adpatee) {
		this.adpatee = adpatee;
	}

	@Override
	public void method1() {
		this.adpatee = adpatee;
	}

}


3.第三种方式(默认的适配器模式)
package com.unis.zzg.defaultadapter;

public interface AbstractService {
	void service1();
	void service2();
	void service3();
}

package com.unis.zzg.defaultadapter;

public class AdapterService implements AbstractService {
	@Override
	public void service1() {
		// TODO Auto-generated method stub

	}
	@Override
	public void service2() {
		// TODO Auto-generated method stub

	}
	@Override
	public void service3() {
		// TODO Auto-generated method stub

	}

}

package com.unis.zzg.defaultadapter;

public class ConcreteService extends AdapterService{

	@Override
	public void service3() {
		System.out.println("service3");
	}

}

小提示:在awt中就使用了默认的适配器模式
例如:
package com.unis.zzg.defaultadapter;

import java.awt.Frame;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Awt {
	
	public static void main(String[] args) {
		Frame frame = new Frame("window");
		frame.addMouseMotionListener(new MouseMotionAdapter() {

			@Override
			public void mouseMoved(MouseEvent e) {
				System.out.println("X:"+e.getX()+"Y:"+e.getY());
			}
		});
		frame.addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent e) {
				System.out.println("window colse");
				System.exit(0);
			}
		});
		frame.setSize(300, 300);
		frame.setVisible(true);
	}

}


通过Adapter就只用实现我们关注的那部分内容了。

你可能感兴趣的:(java)