我需要制作一个程序来运行文本,音频和视频文件,
我创建了一个接口类和三个继承它的类
public interface FileProcess{
public void process();
}
public class TextProcess implements FileProcess{
public void process(){System.out.print("Im Text file")};
}
public class VideoProcess implements FileProcess{
public void process(){System.out.print("Im Video file")};
}
public class AudioProcess implements FileProcess{
public void process(){System.out.print("Im Audio file")};
}
Run Code Online (Sandbox Code Playgroud)
我运行从post请求获取File的测试(例如a.jpg或12.txt或aaa.pdf)如何知道要运行的文件进程?换句话说,我怎么知道应该创建哪个对象进程?
首先请注意您的方法不正确,"缺少a:
public class VideoProcess implements FileProcess{
public void process(){System.out.print("Im Video file")};
// ^ here!
}
Run Code Online (Sandbox Code Playgroud)
要么你没有ImageProcess对象......
这是一个经典的工厂模式.要实现正确的行为,在这种情况下,您可以创建一个通用对象并检查扩展以创建具体实例:
FileProcess process = null;
String filename = "a.jpg";
String extension = filename(0, filename(lastIndexOf(".");
Run Code Online (Sandbox Code Playgroud)
并使用它来选择创建的对象类型:
switch(extension) {
// catch multiple image extensions:
case "jpg":
case "png":
process = new VideoProcess();
break;
// catch text
case "txt":
process = new TextProcess();
break;
// catch multiple audio extensions:
case "wav":
case "mp3":
process = new AudioProcess();
break;
}
Run Code Online (Sandbox Code Playgroud)
另外,我强烈建议使用返回正确对象Factory的链接(步骤3)中描述的类.
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |