简体   繁体   English

java多态创建对象

[英]java polymorphism creating object

I need to make a program that run process on text, audio and video files, 我需要制作一个程序来处理文本,音频和视频文件,

I create an interface class and three class that inherit it 我创建一个接口类和三个继承它的类

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")};
}

I run test that get File from post request (for example a.jpg or 12.txt or aaa.pdf) how can I know what file process to run? 我运行测试以从发布请求中获取文件(例如a.jpg或12.txt或aaa.pdf),我如何知道要运行哪个文件进程? in other words how can I know which object process should be created? 换句话说,我怎么知道应该创建哪个对象进程?

First note your methods are not correct, a " is missing: 首先请注意您的方法不正确,缺少"

public class VideoProcess implements FileProcess{ 
   public void process(){System.out.print("Im Video file")};
   //                                                   ^ here!
}

Either you don't have ImageProcess object... 您要么没有ImageProcess对象...


This is a classic Factory Pattern . 这是经典的工厂模式 To achieve the correct behaviour, in this case, you can create a generic object and check the extension to create concrete instances: 为了实现正确的行为,在这种情况下,您可以创建一个通用对象并检查扩展名以创建具体实例:

FileProcess process = null;
String filename = "a.jpg";
String extension = filename(0, filename(lastIndexOf(".");

And use it to choose what kind of object create: 并使用它来选择创建哪种对象:

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;

}

Also I would highly reccomend to use a Factory class as described in the link ( STEP 3 ) that returns the correct object. 同样,我强烈建议使用链接 (第3步 )中描述的Factory类,该类返回正确的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM