外观模式
为子系统中的一组接口提供一个以自的界面,为模式定义了一个高层接口,这个接口使得这椅子系统更加容易适用。
例子 (买卖股票的基金)
股民可以通过基金更好的理财。
而在背后基金就是利用股民的投资去投资其他股票获得收益。
public class Stock1 {
public void buy(){
System.out.println("Buy...111");
}
public void sell(){
System.out.println("Sell...111");
}
}
Fund(基金类)要有基本的字段。
public class Fund {
Stock1 s1;
Stock2 s2;
Stock3 s3;
Stock4 s4;
public Fund() {
s1 = new Stock1();
s2 = new Stock2();
s3 = new Stock3();
s4 = new Stock4();
}
public void buy(){
s1.buy();
s2.buy();
s3.buy();
s4.buy();
}
public void returns(){
s1.sell();
s2.sell();
s3.sell();
s4.sell();
}
}
public class Client {
public static void main(String[] args) {
Fund fund = new Fund();
fund.buy();
fund.returns();
}
}
总结
-
优点:
1、减少系统相互依赖。
2、提高灵活性。
3、提高了安全性。 -
缺点:不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。
-
使用场景:
1、为复杂的模块或子系统提供外界访问的模块。
2、子系统相对独立。
3、预防低水平人员带来的风险。