这个设计模式我们平时用的太多了,很多时候用到了都不知道,先看代码
/**
* 适配器
* 一个服务如果现有的方法不适应新的需求,可以写一个类进行适配,利用现有的服务进行扩展
*/
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.setType("cat");
animal.setType("white");
System.out.println(animal);
AnimalService animalService = new AnimalService(animal);
AnimalAdapter animalAdapter = new AnimalAdapter(animalService);
animalAdapter.updateType("dog");
animalAdapter.updateColor("black");
System.out.println(animal);
}
}
public class Animal {
private String type;
private String color;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Animal{" +
"type='" + type + '\'' +
", color='" + color + '\'' +
'}';
}
}
public class AnimalAdapter implements Target{
private AnimalService animalService;
public AnimalAdapter(AnimalService animalService){
this.animalService = animalService;
}
@Override
public void updateType(String type) {
animalService.updateType(type);
}
@Override
public void updateColor(String color) {
animalService.getAnimal().setColor(color);
}
}
public class AnimalService {
private Animal animal;
public AnimalService(Animal animal){
this.animal = animal;
}
public void updateType(String type){
this.animal.setType(type);
}
public Animal getAnimal() {
return animal;
}
public void setAnimal(Animal animal) {
this.animal = animal;
}
}
用法:
看完以上代码,觉不觉得就那么回事,不就是一个类封装了另外一个类吗,对嘞,就是这样,懒得解释了。。。