使用组合模式与迭代器模式遍历文件夹中所有文件

这篇博客通过实例展示了如何在Java中结合使用组合模式和迭代器模式来遍历文件夹及其子文件夹中的所有文件。文章适合初学者,作者提醒读者可能需要反复阅读以深入理解,并修复了Head First设计模式书中相关代码的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我写这个例子只是想练习组合模式和迭代器模式的使用,模仿了headfirst设计模式的写法,解决了里面的bug,自己mark一下,对于java初学者不是好理解,so~多看几遍总归有些收获,高手就轻拍吧...


package com.alex.component;

import java.util.Iterator;

@SuppressWarnings("rawtypes")
public abstract class AbstractFile{
	
	public String getFileName() {
		throw new UnsupportedOperationException();
	}

	public String getFileType() {
		throw new UnsupportedOperationException();
	}
	
	public void setFileType(String fileType) {
		throw new UnsupportedOperationException();
	}
	
	public void add(AbstractFile abstractFile){
		throw new UnsupportedOperationException();
	}
	
	public void remove(AbstractFile abstractFile){
		throw new UnsupportedOperationException();
	}
	
	public AbstractFile getChild(int i){
		throw new UnsupportedOperationException();
	}
	
	public void print(){
		throw new UnsupportedOperationException();
	}
	
	public boolean isSelectedFile(String[] configs){
		throw new UnsupportedOperationException();
	}
	
	public abstract Iterator createIterator();

	public boolean isNotTheSelectedFile(String[] configs){
		throw new UnsupportedOperationException();
	}
}

package com.alex.component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.alex.iterator.DirectoryCompositeIterator;

@SuppressWarnings("rawtypes")
public class DirectoryComposite extends AbstractFile {

	private List<AbstractFile> list = new ArrayList<AbstractFile>();;
	private String fileName;
	private String fileType;

	public DirectoryComposite(String fileName,String fileType) {
		this.fileName=fileName;
		this.fileType=fileType;
	}

	@Override
	public String getFileName() {
		return fileName;
	}

	@Override
	public String getFileType() {
		return fileType;
	}

	@Override
	public void add(AbstractFile abstractFile) {
		list.add(abstractFile);
	}

	@Override
	public void remove(AbstractFile abstractFile) {
		list.remove(abstractFile);
	}

	@Override
	public AbstractFile getChild(int i) {
		return (AbstractFile)list.get(i);
	}

	@Override
	public void print() {
		System.out.println(getFileName()+","+getFileType());
		System.out.println("-------------------------");
		
/*		Iterator iterator=list.iterator();
		while(iterator.hasNext()){
			AbstractFile abstractFile=(AbstractFile)iterator.next();
			abstractFile.print();
		}*/

	}

	@Override
	public Iterator createIterator() {
//		retur
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值