After using image processing software to process images, you need to select a format to save. However, the algorithms implemented by various formats at the underlying level are not the same, which just fits the strategy pattern. Write a program that demonstrates how to develop using a combination of policy patterns and simple factory patterns.
The idea is as follows:
1. Use interface to define an interface, and define the save() method in the interface;
2. Define different classes according to the image format, and use the keyword implements to implement the interface in these classes;
3. 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;
4. 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();
}
}
The effect is shown in the picture: