外观模式
模式说明
结构
代码演示
package com.yukiyama.pattern.structure;
/**
* 外观模式
*/
public class FacadeDemo {
public static void main(String[] args) {
// 声明一个外观类
Fund f = new Fund();
System.out.println("====执行基金策略1====");
// 执行既定策略1
f.strategy1();
System.out.println("====执行基金策略2====");
// 执行既定策略2
f.strategy2();
}
}
/**
* 外观类
* 下例为基金,持有三支股票对象,有两个策略方法,封装对三只股票的不同行为组合。
*/
class Fund{
private StockApple sa = new StockApple();
private StockMaotai sm = new StockMaotai();
private NationalDebt nd = new NationalDebt();
public void strategy1() {
sa.buy();
sm.toYuebao();
nd.sell();
}
public void strategy2() {
sa.sell();
sm.sell();
nd.buy();
}
}
/**
* 子系统类
* 苹果公司股票
*/
class StockApple{
public void sell() {
System.out.println("卖出Apple股票");
}
public void buy() {
System.out.println("买入Apple股票");
}
}
/**
* 子系统类
* 茅台股票
*/
class StockMaotai{
public void toYuebao() {
System.out.println("Maotai股票转入余额宝");
}
public void sell() {
System.out.println("买入Maotai股票");
}
}
/**
* 子系统类
* 国债
*/
class NationalDebt{
public void sell() {
System.out.println("卖出国债");
}
public void buy() {
System.out.println("买入国债");
}
}Last updated