码迷,mamicode.com
首页 > Web开发 > 详细

JS 组合模式

时间:2015-04-21 22:26:01      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

/**
* 组合模式应用的场景和特点:
* 场景:
* 1 存在一批组织成某种层次体系的对象
* 2 希望对这批对象或其中的一部分对象实施一个操作
*
* 应用特点:
* 1 组合模式中只有两种类型对象:组合对象、叶子对象
* 2 这两种类型都实现同一批接口
* 3 一般我们会在组合对象中调用其方法并隐式调用"下级对象"的方法(这里我们一般采用递归的形式去做)
*
*/
/*
* 场景模拟:
* -> 公司
  * -> 北京分公司
    * -> 财务部门
      * -> 张1
      * -> 张2
      * -> 张3
    * -> 销售部门
      * -> 张4
      * -> 张5
      * -> 张6
  -> 长沙分公司
    * -> 财务部门
      * -> 张7
      * -> 张8
      * -> 张9
    * -> 销售部门
      * -> 张10
      * -> 张11
      * -> 张12
*
* 实际的任务具体是落实到人上去实施的 也就是说只有人才具有具体的方法实现
*
*/

<script type=text/javascript charset=utf-8>
<!--JS设计模式(组合模式 应用场景)-->
//公司
var Org=function(name){
this.name=name;
this.depts=[];
};
Org.prototype={
constructor:Org,
addDepts:function(child){
this.depts.push(child);
return this;//链式调用
},
getDepts:function(){
return this.depts;
}
};
//部门
var Dept=function(name){
this.name=name;
this.persons=[];
};
Dept.prototype={
constructor:Dept,
addPersons:function(child){
this.persons.push(child);
return this;//链式调用
},
getPersons:function(){
return this.persons;
}
};
//人员
var Person=function(name){
this.name=name;
};
Person.prototype={
constructor:Person,
harkWorking:function(){
document.write(this.name+"努力");
},
sleeping:function(){
document.write(this.name+"睡觉");
}
};
var p1=new Person("张三1");
var p2=new Person("张三2");
var p3=new Person("张三3");
var p4=new Person("张三4");

var dept1=new Dept("财务部");
dept1.addPersons(p1).addPersons(p2);
var dept2=new Dept("销售部");
dept2.addPersons(p3).addPersons(p4);

var org=new Org("JALJA");
org.addDepts(dept1).addDepts(dept2);
//让具体的一个人去工作
for(var i=0,depts=org.getDepts();i<depts.length;i++){
alert(org.getDepts);
var dept=depts[i];
for(var g=0,persons=dept.getPersons();g<persons.length;g++){
alert(persons);
if(persons[g].name==="张三1"){
persons[g].harkWorking();
}
}
}
</script>

JS 组合模式

标签:

原文地址:http://www.cnblogs.com/jalja/p/4445569.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!