java设计模式之组合模式

来源:互联网 发布:淘宝查假货 编辑:程序博客网 时间:2024/05/19 08:38

生活例子说明:今天是妹子的生日,所以你答应给她买一件礼物,于是你们逛街去了。逛到一家店,妹子刚好看上了一件上衣,一条裤子,一个包和一对鞋,她要求你买给她,你当然不肯啦因为你当初答应只送她一件礼物,这时,妹子机智地使用了 组合模式的思想说道这四件组合起来刚好是一套啊,然后。。。呵呵

 

组合模式就是将对象以树形结构组织起来,以达到“部分-整体”的层次结构,使得客户(你)对单个对象和组合对象(1件 VS 1套)的使用具有一致性(都是付一次钱。。。)。

 

下面是代码实现的妹子买礼物:

interface Gift{void Pay();void Add(Gift gift);}class GiftSingle implements Gift{private String giftName;public GiftSingle(String giftName){this.giftName = giftName;}public void Add(Gift gift){}public void Pay(){System.out.println("我买了" + giftName + "->_<-!!");}}class GiftComposite implements Gift{List<Gift> gifts;String m_name;public GiftComposite(){gifts = new ArrayList<Gift>();}public void Add(Gift gift){gifts.add(gift);}public void Pay(){for(Gift g : gifts)g.Pay();}}public class girl {public static void main(String[] args) {System.out.println("20岁生日");Gift singleGiftFor20 = new GiftSingle("鞋子");singleGiftFor20.Pay();System.out.println("21岁生日,变狡诈了呵呵");Gift compositeGiftFor21 = new GiftComposite();//打包,都要!全部打包成一套,呵呵!!!compositeGiftFor21.Add(new GiftSingle("上装"));compositeGiftFor21.Add(new GiftSingle("下装"));compositeGiftFor21.Add(new GiftSingle("包包"));compositeGiftFor21.Add(new GiftSingle("鞋子"));compositeGiftFor21.Pay();System.out.println("22岁生日,万恶的程序员妹子!!!!");Gift compositeGiftFor22 = new GiftComposite();//先逛一下化妆品区嘛,不急!!//先买些化妆品compositeGiftFor22.Add(new GiftSingle("香水"));compositeGiftFor22.Add(new GiftSingle("粉底"));compositeGiftFor22.Add(new GiftSingle("眼影"));//不急,先别买单,上楼看看衣服嘛//然后看中一件衣服。。。Gift singleGiftFor22 = new GiftSingle("T-shirt");//然后狡黠的用大招——组合模式!!!Gift totalGiftFor22 = new GiftComposite();totalGiftFor22.Add(compositeGiftFor22);totalGiftFor22.Add(singleGiftFor22);//OK,可以买单了。。。>_<totalGiftFor22.Pay();}}

组合模式的好处:

客户代码中任何用到基本对象的地方都可以使用组合对象,客户不需要知道到底是在处理一个叶子节点还是处理一个组合节点。
 

0 0