Adapter模式

将一个类的接口转换成客户希望的另外一个接口,使原本由于接口不兼容而不能在一起工作的类可以一起工作

Adaptee.java

package com.gary.designpattern.adapter;

/**
 * 需要适配的目标
 * @author gary
 *
 */
public interface Adaptee {
	public void doSomethingSpecial();
}

 

AdapteeImpl.java

package com.gary.designpattern.adapter.impl;

import com.gary.designpattern.adapter.Adaptee;

/**
 * 需要适配的类
 * @author gary
 *
 */
public class AdapteeImpl implements Adaptee{
	@Override
	public void doSomethingSpecial(){
		System.out.println("do something special");
	}
}

 

Target.java

package com.gary.designpattern.adapter;

/**
 * 客户所期待的接口,也可以是类
 * @author gary
 *
 */
public interface Target {
	public void doSomething();
}

 

TargetImpl.java

package com.gary.designpattern.adapter.impl;

import com.gary.designpattern.adapter.Target;

/**
 * 客户所期待的接口实现,也可以是类
 * @author gary
 *
 */
public class TargetImpl implements Target{
	@Override
	public void doSomething(){
		System.out.println("do something");
	}
}

 

Adapter.java

package com.gary.designpattern.adapter;

import com.gary.designpattern.adapter.impl.AdapteeImpl;

/**
 * 定义一个Adaptee对象,把原接口转换成目标接口
 * @author gary
 *
 */
public class Adapter implements Target{
	private Adaptee adaptee = new AdapteeImpl();
	
	@Override
	public void doSomething(){
		adaptee.doSomethingSpecial();
	}
}

 

Test.java

package com.gary.designpattern.adapter;

public class Test {
	public static void main(String[] args) {
		Target target = new Adapter();
		target.doSomething();
	}
}

 

你可能感兴趣的:(java,设计模式)