0

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? in other words how can I know which object process should be created?

3
  • 1
    Your question is totally unclear , and how does this linked to polymorphism . just because your implementing the interface ? Commented May 19, 2015 at 7:24
  • What is it that you want here? Commented May 19, 2015 at 7:26
  • header will tell you the type of file which you can use as switch case to create appropriate object using a static factory Commented May 19, 2015 at 7:26

1 Answer 1

5

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...


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.

Sign up to request clarification or add additional context in comments.

1 Comment

nice to hear, if doubts following link or answer provided let me know, link explains really nice how to create a simple and great factory pattern easily that will make your code rock ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.