Composite 模式

 

定义 :Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and cpmpositions of objects uniformly

将对象组合成树形结构以表示‘部分整体’ 层次结构 ,是的用户对单个对象和组合对象有一致性

 

自己写了一个例子 感觉很不恰当

组合模式有两种情况 ,透明的组合模式,和安全的组合模式。

 

透明的组合模式就是把composite中的属性和方法抽象到 Component 中 ,这样会有些问题,比如  left 节点会包含很多无用的数据和方法 。但这有一个好处就是对 场景类来说所有的对象,无论是单个对象还是组合对象的处理都相同,这样满足依赖倒置原则,也很好的利用多台机制。  另外一种方法就是 安全方法 ,这个方法使实现类与抽象类接口不同,不过这样会违反依赖倒置等原则。 需要注意 。。。

 

下面是一个例子

http://wenku.baidu.com/view/3bf40c1614791711cc7917e3.html

 

我自己写的一个。

package Composite;

import java.util.ArrayList;

public class Branch extends Corp{

	ArrayList<Corp> list=new ArrayList<Corp>();
	public Branch(String name, int salary, String position) {
		super(name, salary, position);
root   10000   manager
xiaotoumu   5000   xiaotoumu
xiaotoumu   5000   xiaotoumu
xiaodi2   3000   xiaodi2
xiaodi   4000   xiaodi

}public void addElements(Corp c){list.add(c);} public ArrayList<Corp> getElements(){ return list; } }


 

package Composite;

import java.util.ArrayList;

public class Branch extends Corp{

	ArrayList<Corp> list=new ArrayList<Corp>();
	public Branch(String name, int salary, String position) {
		super(name, salary, position);
	}
	public void addElements(Corp c){
		list.add(c);
		
	}
    public ArrayList<Corp> getElements(){
    	return list;
    }
  

}


 

package Composite;

import java.util.ArrayList;

public class Branch extends Corp{

	ArrayList<Corp> list=new ArrayList<Corp>();
	public Branch(String name, int salary, String position) {
		super(name, salary, position);
	}
	public void addElements(Corp c){
		list.add(c);
		
	}
    public ArrayList<Corp> getElements(){
    	return list;
    }
  

}


 

package Composite;

import java.util.ArrayList;

public class Client {
	public static String getTreeInfo(Branch b){
		ArrayList<Corp> list =b.getElements();
		
		String info=b.getInfo()+"\n";
		for(Corp c:list){
			if(c instanceof Leaf)
				info=info+c.getInfo()+"\n";
			else
				info=info+c.getInfo()+"\n"+getTreeInfo((Branch)c);
		}
   

		return info;
	}
	public static void main(String []args){
		Branch root=new Branch("root",10000,"manager");
		Branch xiaotoumu=new Branch("xiaotoumu",5000,"xiaotoumu");
		Leaf xiaod1=new Leaf("xiaodi",4000,"xiaodi");
		Leaf xiaod2=new Leaf("xiaodi2",3000,"xiaodi2");
		
		root.addElements(xiaotoumu);
		xiaotoumu.addElements(xiaod2);
		xiaotoumu.addElements(xiaod1);
		
		
		System.out.println(Client.getTreeInfo(root));
	}

}


 

可以看到,这个是安全模式下的组合模式,Client 知道了太多关于具体类实现的事情,违反了面向接口编程的约定。

 

我们在项目中应该 根据需求来合理选择

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值