Composite 模式初探
Composite作为设计模式结构化模式的一种,有效的使得原本一组分离的组件可以随意的进行有机的结合,然后通过开发公用接口方便外部调用
以下是个人理解后的一个案例
随着人们对银行个人理财的重视,越来越多的人会去银行进行个人理财,而个人理财的形式也分门别类,人们会把不同类型理财产品的捆绑在一起进行投资,以便减少风险,还可以对多个捆绑的综合产品进行投资以进一步在保持本金安全的前提下,扩大投资的回报率。
customer类模拟银行理财行为
package com.lee.composite; public class Customer { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("客户去银行理财"); FinanceProductsComposite f = new FinanceProductsComposite(); StockALeaf sa = new StockALeaf(); StockALeaf saa = new StockALeaf(); StockBLeaf sb = new StockBLeaf(); FundALeaf fa = new FundALeaf(); FundBLeaf fb = new FundBLeaf(); FundBLeaf fbb = new FundBLeaf(); StockProductsComposite spc = new StockProductsComposite(); FundsProductsComposite fpc = new FundsProductsComposite(); spc.addComposite(sa); spc.addComposite(saa); spc.addComposite(sb); fpc.addComposite(fa); fpc.addComposite(fb); fpc.addComposite(fbb); f.addComposite(spc); f.addComposite(fpc); System.out.println("银行给出理财方案"); f.purchase(); } }
FinanceProductsComposite为公用接口
package com.lee.composite; import java.util.ArrayList; import java.util.List; public class FinanceProductsComposite { List<FinanceProductsComposite> childCompositeList = new ArrayList<FinanceProductsComposite>() ; FinanceProductsComposite parentComposite ; public List<FinanceProductsComposite> getChild() { return childCompositeList; } public void addComposite(FinanceProductsComposite financeProductsComposite) { childCompositeList.add(financeProductsComposite); financeProductsComposite.setParent(this); } public FinanceProductsComposite getParent() { return parentComposite; } private void setParent(FinanceProductsComposite financeProductsComposite) { parentComposite = financeProductsComposite; } public void removeComposite(FinanceProductsComposite financeProductsComposite) { childCompositeList.remove(financeProductsComposite); financeProductsComposite.removeParent(); } public void removeParent() { parentComposite = null; } public void purchase() { for(FinanceProductsComposite f : childCompositeList) { f.purchase(); } } public void sale() { for(FinanceProductsComposite f : childCompositeList) { f.purchase(); } } }
FundsProductsComposite与StockProductsComposite为两大产品组合
package com.lee.composite; public class FundsProductsComposite extends FinanceProductsComposite { } package com.lee.composite; public class StockProductsComposite extends FinanceProductsComposite { }
其他为具体的叶节点
package com.lee.composite; public class StockALeaf extends StockProductsComposite { public void purchase() { System.out.println("buy $20 stock A"); } public void sale() { System.out.println("sale $20 stock A"); } } package com.lee.composite; public class FundALeaf extends FundsProductsComposite { public void purchase() { System.out.println("buy $20 fund A"); } public void sale() { System.out.println("sale $20 fund A"); } }