javaScript——组合模式

<script>
		//组合模式就是用小的对象来构建更大的对象,将对象组成树形结构,以部门-整体的层次结构.组合模式可以通过对象的多态性表现,使得用户对单个对象和组合对象的使用具有一致性
		// js实现组合模式的难点在于要保证组合对象和叶对象拥有相同的方法.组合对象和叶对象本质上是有区别的,叶对象下面没有子节点
		var closeDoorCommand = {
			excute:function(){
				console.log('关门')
			}
		};
		var openPcCommand = {
			excute:function(){
				console.log('开电脑')
			}
		};
		var openCCTVCommand = {
			excute:function(){
				console.log('开电视')
			}
		};
		var openQQ={
			excute:function(){
				console.log('开qq')
			}
		}
		// 通过返回一个对象来保存函数
		var MacroCommand= function(){
			return {
				commandList:[],		//用来保存每一个子对象
				add:function(command){
					this.commandList.push(command);
				},
				excute:function(){
					for(var i =0,command;command=this.commandList[i++];){
						command.excute()
					}
				}
			}
		}
// 
// 通过闭包实现,用一个数组来保存每一个子对象
		var macroCammand1=MacroCommand();
		var macroCammand2=MacroCommand();
		var macroCammand=MacroCommand();		//macroCammand是一个对象
		macroCammand1.add(closeDoorCommand);
		macroCammand1.add(openPcCommand);
		macroCammand2.add(openCCTVCommand);
		macroCammand2.add(openQQ);
		macroCammand.add(macroCammand1);
		macroCammand.add(macroCammand2);
		macroCammand.excute();
	</script>
	<script>
		// 组合对象保存了它下面的子节点的引用.
		var Folder=function(name){
			this.name=name;
			this.parent=null;
			this.files=[];
		}
		Folder.prototype.add=function(file){
			file.parent=this;		//设置父对象
			this.files.push(file)
		}
		Folder.prototype.scan=function(){
			console.log('开始扫描文件夹:'+this.name);
			for(var i=0,file;file=this.files[i++];){
				file.scan();
			}
		}
		Folder.prototype.remove=function(){
			if(!this.parent){
				return;
			}
			console.log(this.parent.files)
			for(var files=this.parent.files,l=files.length-1;l>=0;l--){
				
				var file=files[l];
				if(file===this){
					files.splice(l,1)
				}
			}
		}
		var  File=function(name){
			this.name=name;
			this.parent=null;
		}
		File.prototype.add=function(){
			throw new Error('不能添加在文件下m面');
		}
		File.prototype.scan=function(){
			console.log('文件扫描'+this.name);
		}
		File.prototype.remove=function(){
			if(!this.parent){
				return ;
			}
			for(var files=this.parent.files,l=files.length-1;l>=0;l--){
				var files=files[l];
				if(files===this){
					files.splice(l,1);
				}
			}
		}
		var folder=new Folder('学习资料');
		var folder1=new Folder('Javascript');
		var file1=new Folder('深入浅出node');
		folder1.add(new File('llll'));
		folder.add(folder1);
		folder.add(file1);
		folder1.remove();
		folder1.scan();
	</script>

猜你喜欢

转载自blog.csdn.net/Miss_hhl/article/details/103703214