Java implementation policy Pattern usage example _java

Source: Internet
Author: User

Ideas are as follows:

Use interface to define an interface that defines the save () method in the interface;
Define the different classes according to the picture format, and use the keyword implements to implement the interface respectively in these classes;
Creates a class that implements the selection, in which the method of implementing the selection is defined, and the method returns a value of the corresponding picture save class;
Implement an 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 ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.