After using the image processing software to process the picture, you need to choose a format to save. However, various formats are implemented at the bottom of the algorithm is not the same, this is suitable for the policy model. Write a program that demonstrates how to use a policy pattern to develop with a simple factory pattern combination.
Ideas are as follows:
1. Use interface to define an interface to define the Save () method in the interface;
2. Define different classes according to the picture format, and use the keyword implements to implement the interface in these classes respectively;
3. Create a class that implements the selection, in which you define the method that implements the selection, which returns a value of the corresponding picture save class;
4. Implement the interface in the main method.
The code is as follows:
Copy Code code as follows:
Public interface Imagesaver {
void Save ();//define Save () method
}
public class Gifsaver implements Imagesaver {
@Override
public void Save () {//Implementation 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 picture in PNG format");
}
}
public class Typechooser {
public static Imagesaver Getsaver (String type) {
if (Type.equalsignorecase ("GIF")) {//Use if Else statement to determine the type of picture
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 ("User selected GIF format:");
Imagesaver saver = typechooser.getsaver ("gif");//Get an object to save a picture as a GIF type
Saver.save ();
System.out.print ("User selected JPEG format:")//Get object to save picture as JPEG type
Saver = Typechooser.getsaver ("JPEG");
Saver.save ();
System.out.print ("User selected PNG format:")//Get object to save picture as PNG type
Saver = Typechooser.getsaver ("PNG");
Saver.save ();
}
}
Effect as shown: