Adapter Pattern

Adapter Pattern

Adapter pattern works as a bridge between two incompatible interfaces. It converts interface A into another interface B so that interface A could be compatible with those class of interface B. A real life example could be a case of travaling to another country, in the hotel, you want to charge your mobile, but you find that the socket is absolutly not the same as the ones of your country. So now we need an adapter to charge your mobile.

Example

We have interfaces Duck and Turkey. Now we want an Adapter to convert Turkey into Duck, so in this way, on client side, we see only Ducks! (So turkey classes would be compatible with methods for interface Duck)

Duck:


public interface Duck {
	public void quack();
	public void fly();
}

public class GreenHeadDuck implements Duck {

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

	@Override
	public void fly() {
		System.out.println("I am flying a long distance");
	}
}
复制代码

Turky:

public interface Turkey {
	public void gobble();
	public void fly();
}

public class WildTurkey implements Turkey {

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

	@Override
	public void fly() {
		System.out.println("I am flying a short distance");
	}
}
复制代码

Adapter Type

To realize an adapter, we have two ways:

  1. Object Adapter - uses composition and can wrap classes or interfaces, or both. It can do this since it contains, as a private, encapsulated member, the class or interface object instance it wraps.
  2. Class Adapter - uses inheritance and can only wrap a class. It cannot wrap an interface since by definition it must derive from some base class.

Object Adapter

public class TurkeyAdapter implements Duck {

	private Turkey turkey;
	
	public TurkeyAdapter(Turkey turkey) {
		this.turkey=turkey;
	}

	@Override
	public void quack() {
		turkey.gobble();
	}

	@Override
	public void fly() {
		turkey.fly();
	}
}
复制代码

Class Adapter

public class TurkeyAdapter extends WildTurkey implements Duck {

	@Override
	public void quack() {
		super.gobble();
	}

	@Override
	public void fly() {
		super.fly();
	}
}
复制代码

Test

public class MainTest {
	public static void main(String[] args) {
		
		// WildTurkey turkey = new WildTurkey();
		// Duck duck = new TurkeyAdapter(turkey);

		Duck duck = new TurkeyAdapter();

		duck.quack();
		duck.fly();

	}
}
复制代码

So on client side, we only see a duck! But it performs like a turkey :D

Ref

Reprint

Reprint

猜你喜欢

转载自juejin.im/post/5ce2ab3bf265da1bbc6fa7dc