A simple application implementation of the Java policy pattern
- 2020-04-01 02:59:32
- OfStack
After using the image processing software to process the image, you need to choose a format to save. However, different formats implement different algorithms at the bottom, which is just right for the policy 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, in which the save() method is defined;
2. Define different classes according to the image format, and implement an interface in each of these classes using the keyword implements;
3. Create a class to implement the selection, and define the method to implement the selection in this class. The method returns the value to save the class for the corresponding picture;
Implement the interface in the main method.
The code is as follows:
public interface ImageSaver {
void save();//Define the save() method
}
public class GIFSaver implements ImageSaver {
@Override
public void save() {//Implement the save() method
System.out.println(" Save the picture as GIF format ");
}
}
public class JPEGSaver implements ImageSaver {
@Override
public void save() {
System.out.println(" Save the picture as JPG format ");
}
}
public class PNGSaver implements ImageSaver {
@Override
public void save() {
System.out.println(" Save the picture as 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 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 selects GIF Format: ");
ImageSaver saver = TypeChooser.getSaver("GIF");//Gets an object that saves the image as a GIF
saver.save();
System.out.print(" The user selects JPEG Format: ");//Gets an object that saves the image as a JPEG
saver = TypeChooser.getSaver("JPEG");
saver.save();
System.out.print(" The user selects PNG Format: ");//Gets an object of type PNG to save the image
saver = TypeChooser.getSaver("PNG");
saver.save();
}
}
The effect is as follows:
< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201402/2014224160321413.png" >