我在 Bharath Thippireddy 设计模式课程中找到了最清晰、最真实的例子。
我们有WeatherUI 类,它通过邮政编码查找温度,我们有WeatherFinderImpl 类,它通过城市名称知道温度,所以我们需要创建WeatherAdapter 类,它将采用邮政编码,将其更改为城市名称并调用@ 987654324@ 类返回适当的温度。
WeatherUi类:
public class WeatherUI {
public void showTemperature(int zipcode) {
//I just have zipcode
}
}
和WeatherFinder接口:
public interface WeatherFinder {
int find(String city);
}
和WeatherFinderImpl只能通过城市名称查找温度:
public class WeatherFinderImpl implements WeatherFinder{
@Override
public int find(String city) {
return 25;
}
}
将这三个放在WeatherUI 类中,我们可以创建一个将邮政编码转换为城市的方法,或者我们可以创建一个新的适配器类:
public class WeatherAdapter {
public int findTemperature(int zipcode){
String city = null;
//here most probably we would take it from db, in example hardcode is enough
if(zipcode == 63400){
city = "Ostrow Wielkopolski";
}
WeatherFinder finder = new WeatherFinderImpl();
int temperature = finder.find(city);
return temperature;
}
}
并在WeatherUI 中调用它:
public class WeatherUI {
public void showTemperature(int zipcode) {
WeatherAdapter adapter = new WeatherAdapter();
System.out.println(adapter.findTemperature(63400));
}
}
对其进行测试很简单:
public static void main(String[] args) {
WeatherUI ui = new WeatherUI();
ui.showTemperature(63400);
}