Design Patterns (7) - adapter mode

Adapter (Adapter) mode, the interface of a class, is converted into another interface to customer expectations. Adapter so that the original interface is not compatible with the class can collaborate seamlessly. This mode allows customers to decouple from the interface, if at some time, we want to change the interface, the adapter can be changed up part of the package, customers do not have to deal with different interfaces and each modification follow.

The picture shows the adapter mode class

Directly following a specific example will be described

We have a duck Interface

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

There is also a turkey Interface

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

Now suppose we are missing objects duck, turkey would like to use some of the objects to impersonate. Obviously, because of the different interfaces turkey, so we can not make use of them openly. This requires a write adapter

import java.util.Random;

public class DuckAdapter implements Turkey {//让鸭子看起来像火鸡
	Duck duck;
	Random rand;
 
	public DuckAdapter(Duck duck) {
		this.duck = duck;
		rand = new Random();
	}
    
	public void gobble() {
		duck.quack();
	}
  
	/* 虽然两个接口都具备fly()方法,但火鸡飞行距离很短,不像鸭子可以长途飞行。 要让鸭子的飞行和火鸡的飞行能够对应,必须连续五次调用火鸡的fly()来完成。 */
	public void fly() {
		if (rand.nextInt(5)  == 0) {
		     duck.fly();
		}
	}
}

Adapter pattern is full of good OO design principles: object composition to modify the interface package is fitter: This approach has the added advantage that is adapted Any subclass can be used with the adapter. In addition, this model binds the client and interfaces together, rather than bind and realize that we can use several adapters, each of which is responsible for converting the class background of different groups. Alternatively, you can also add new implementations, as long as they comply with the objectives interfaces can be.

In fact, a total of "two kinds" adapter: Object Adapter and Class Adapter , previously described is an object adapter, the adapter on the class, you need multiple inheritance to achieve it, and the Java class does not support multiple inheritance, so we do not pay more description given here only adapter class class diagram:

Published 295 original articles · won praise 37 · views 30000 +

Guess you like

Origin blog.csdn.net/tianshan2010/article/details/104713988