The idea is as follows:
Use interface to define an interface, and define the save() method in that interface;
Define different classes according to the image format, and use the keyword implements to implement the interface in these classes;
Create a class that implements selection, defines the method that implements selection in this class, and the return value of the method is the corresponding image saving class;
Implement the interface in the main method.
The code is as follows:
The code copy is as follows:
public interface ImageSaver {
void save();//Define save() method
}
public class GIFSaver implements ImageSaver {
@Override
public void save() {//Implement save() method
System.out.println("Save the picture in GIF format");
}
}
public class JPEGSaver implements ImageSaver {
@Override
public void save() {
System.out.println("Save the picture in JPG format");
}
}
public class PNGSaver implements ImageSaver {
@Override
public void save() {
System.out.println("Save the picture in PNG format");
}
}
public class TypeChooser {
public static ImageSaver getSaver(String type) {
if (type.equalsIgnoreCase("GIF")) {//Use the if else statement to determine the type of the image
return new GIFSaver();
} else if (type.equalsIgnoreCase("JPEG")) {
return new JPEGSaver();
} else if (type.equalsIgnoreCase("PNG")) {
return new PNGSaver();
} else {
return null;
}
}
}
public class User {
public static void main(String[] args) {
System.out.print("The user selected the GIF format:");
ImageSaver saver = TypeChooser.getSaver("GIF");//Get the object that saves the image as GIF type
saver.save();
System.out.print("The user selected JPEG format:");//Get the saved image as JPEG type object
saver = TypeChooser.getSaver("JPEG");
saver.save();
System.out.print("The user selected PNG format:");//Get the object that saves the image as PNG type
saver = TypeChooser.getSaver("PNG");
saver.save();
}
}