简体   繁体   中英

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


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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