题记
码农A:我在做一件大事情,步骤是这样的:买菜,洗菜,切好,烹饪,放调料。
码农B:stop,stop,你直接说你要炒菜不就完了吗。。。
概述
为了提高代码利用率,我们一般会把功能封装成一个一个方法,可是当要完成一个功能时,我们需要调用很多个方法时,我们可以在代码中一个一个方法地挨着调用,我们也可以在写一个方法来专门封装这个功能,这个方法就是所谓的外观。
外观模式
外观模式很简单,它就是对方法的封装,把原来分散的多个方法重新写在一个新方法里,这个新方法就是外观,可以说是一种编程的思想吧。接下来外出上面炒菜的例子:
菜市场提供蔬菜:
public class Market {
public void getVegetable(){
System.out.println("获取蔬菜");
}
}
人负责洗和切蔬菜:
public class Person {
public void washVegetable(){
System.out.println("洗蔬菜");
}
public void cutVegetable(){
System.out.println("切蔬菜");
}
}
调味品负责加盐和味精:
public class Condiment {
public void getSalt(){
System.out.println("放盐");
}
public void getAginomoto(){
System.out.println("放味精");
}
}
烹饪类负责提供一个烹饪外观(cook函数):
public class Cook {
private Condiment condiment;
private Market market;
private Person person;
public Cook(Condiment condiment, Market market, Person person) {
this.condiment = condiment;
this.market = market;
this.person = person;
}
public void cook(){
market.getVegetable();
person.washVegetable();
person.cutVegetable();
condiment.getSalt();
condiment.getAginomoto();
finishCook();
}
public void finishCook(){
System.out.println("烹饪完成");
}
}
客户端代码:
public class Client {
public static void main(String[] args) {
Market market = new Market();
Person person = new Person();
Condiment condiment = new Condiment();
Cook cook = new Cook(condiment,market,person);
cook.cook();
}
}
具体结果: