The Java implementation policy pattern USES the example

  • 2020-04-01 03:00:30
  • OfStack

The idea is as follows:

Use interface to define an interface where the save() method is defined.
Defines different classes based on the image format, and implements an interface in each of these classes using the keyword implements.
Creates a class to implement the selection, defines the method to implement the selection in the class, the method returns the value to save the class for the corresponding image;
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();
    }
}


Related articles: