题目:通过购买基金来购买股票A、B、C
public class StockA { public void buy() { System.out.println("股票A买入"); } public void sell() { System.out.println("股票A卖出"); }}public class StockB { public void buy() { System.out.println("股票B买入"); } public void sell() { System.out.println("股票B卖出"); }}public class StockC { public void buy() { System.out.println("股票C买入"); } public void sell() { System.out.println("股票C卖出"); }}
public class Fund { StockA stockA; StockB stockB; StockC stockC; public Fund() { stockA = new StockA(); stockB = new StockB(); stockC = new StockC(); } public void buyFund() { stockA.buy(); stockB.buy(); stockC.buy(); } public void sellFund() { stockA.sell(); stockB.sell(); stockC.sell(); }}
public class Test { public static void main(String args[]) { Fund fund = new Fund(); fund.buyFund(); fund.sellFund(); }}
打印结果:
股票A买入股票B买入股票C买入股票A卖出股票B卖出股票C卖出
其实很简单,就是将StockA、StockB、StockC封装起来,我们只要调用Fund的API就可以了