In-depth analysis and examples of policy patterns in java

Source: Internet
Author: User

The Strategy Pattern reflects two basic object-oriented design principles.

-Encapsulate the concept of change
-Use interfaces in programming instead of implementing interfaces

Rule mode definition
-Define a set of algorithms, encapsulate each algorithm, and make them interchangeable.
-The policy mode enables these algorithms to change without affecting each other when the client calls them.

Procedure
-1. Define a public interface for the policy object.
-2. Write a policy class that implements the above public interface
-3. Save a pair of policy
.
-4. Implement the policy object
Or use the constructor.
Assign value

Solution

Extract frequently changed or potentially changed parts of a class as an interface, and then include the instance of this object in the class, this type of instance can call the class behavior that implements this interface at will during runtime.
For example, you can define a series of algorithms, encapsulate each algorithm, and make them replace each other, so that the algorithm can change independently of the customers who use it. This is the rule mode.


Applicability

Many related classes only have different behaviors. "Policy" provides a method to configure a class with one of multiple actions. That is, a system must dynamically select one of several algorithms.
It is used when an application needs to implement a specific service or function and has multiple implementation methods.

A class defines multiple behaviors, and these behaviors appear in the form of multiple conditional statements in the operations of this class. Move related condition branches into their respective Strategy classes to replace these condition statements.

Advantages

1. Dynamically changing object behavior

Disadvantages

1. The client must know all the policy classes and decide which one to use.
2. Policy mode will generate many strategies


Composition

Context: A ConcreteStrategy object is used for configuration. Maintain a reference to the Strategy object. You can define an interface to allow Strategy to access its data.
Abstract Strategy: defines the public interfaces of all supported algorithms. Context uses this interface to call a ConcreteStrategy-defined algorithm.
ConcreteStrategy: a specific algorithm is implemented using the Strategy interface.


Application

The scenario is as follows. Liu Bei is about to marry his wife in Jiangdong. Zhuge Liang gave Zhao cloud three tips, saying that the split by Tianji can solve the thorny problem. There are three elements in the scenario: three tips (specific strategies), one tip (environment), and Zhao Yun (caller ).

 

The code is as follows: Copy code

Abstract Strategy)
Public interface Strategy {
Public void operate ();
}

Three implementation classes (ConcreteStrategy ):
Tip 1: Wu Guo
Public class BackDoor implements IStrategy {
@ Override
Public void operate (){
System. out. println ("ask Joe for help and let Wu Guotai put pressure on Sun Quan so that Sun Quan cannot kill Liu Bei ");
     }
} Tip 2: ask Wu Guotai to open the green light
Public class GivenGreenLight implements IStrategy {
@ Override
Public void operate (){
System. out. println ("ask Wu Guotai to open a green light and allow ");
     }
} Tip 3: after Mrs Sun is disconnected, the defender will be blocked.
Public class BlackEnemy implements IStrategy {
@ Override
Public void operate (){
System. out. println ("when Mrs Sun is disconnected, block the pursuit of troops ");
     }
}
Context)
Public class Context {
Private Strategy strategy;
// Which method does the constructor want you to use?
Public Context (Strategy strategy ){
This. strategy = strategy;
     }
Public void setStrategy (Strategy strategy ){
This. strategy = strategy;
     }
Public void operate (){
This. strategy. operate ();
     }
}

Example

After image processing software is used to process images, you need to select a format for saving. However, the underlying implementation algorithms of various formats are not the same, which is suitable for the policy mode. Write a program to demonstrate how to use a combination of policy mode and simple factory mode for development
The idea is as follows:

Use interfaces to define an interface, and define the save () method in this interface;
Define different classes based on the image format, and use the keyword implements in these classes to implement the interface;
Create an implementation selection class and define the implementation selection method in this class. The return value of this method is the corresponding image storage class;
Implement interfaces in the main method.
The code is as follows:

The code is as follows: Copy code


Public interface ImageSaver {
Void save (); // defines the save () method
}

Public class GIFSaver implements ImageSaver {
@ Override
Public void save () {// implement the save () method
System. out. println ("save the image as GIF ");
    }
}

Public class extends saver implements ImageSaver {

@ Override
Public void save (){
System. out. println ("save the image as JPG ");
    }
}

Public class PNGSaver implements ImageSaver {

@ Override
Public void save (){
System. out. println ("save the image as PNG ");
    }

}

Public class TypeChooser {
Public static ImageSaver getSaver (String type ){
If (type. Define signorecase ("GIF") {// use the if else statement to determine the image type
Return new GIFSaver ();
} Else if (type. equalsIgnoreCase ("JPEG ")){
Return new inclusaver ();
} 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"); // Obtain the object that saves the image as GIF.
Saver. save ();
System. out. print ("JPEG format selected:"); // Obtain the object whose image is saved as JPEG.
Saver = TypeChooser. getSaver ("JPEG ");
Saver. save ();
System. out. print ("PNG format selected:"); // Obtain the object whose image is saved as PNG.
Saver = TypeChooser. getSaver ("PNG ");
Saver. save ();
    }
}


Java sorting policy mode implementation:

There is such a class:

The code is as follows: Copy code

Public class Person {

Private int id;

Private String name;

Private int age;

}

Requirement: if there are several class Person objects in a List, sort them by name,

Sort by age and id (there must be two sorting methods: Forward and reverse ). If the age or name is the same, the IDS are sorted in the forward order.

The following is the source code.

The code is as follows: Copy code

Class Person

Package com. jack. SortStrategy;

Public class Person {
Private int id;
Private String name;
Private int age;
 
Public Person (int id, String name, int age ){
This. id = id;
This. age = age;
This. name = name;
 }
/**
* @ Return the id
*/
Public int getId (){
Return id;
 }
/**
* @ Param id the id to set
*/
Public void setId (int id ){
This. id = id;
 }
/**
* @ Return the name
*/
Public String getName (){
Return name;
 }
/**
* @ Param name the name to set
*/
Public void setName (String name ){
This. name = name;
 }
/**
* @ Return the age
*/
Public int getAge (){
Return age;
 }
/**
* @ Param age the age to set
*/
Public void setAge (int age ){
This. age = age;
 }
}
Class IdOrder

Package com. jack. SortStrategy;

Import java. util. Comparator;

Public class IdOrder implements Comparator <Person> {

@ Override
Public int compare (Person o1, Person o2 ){
// TODO Auto-generated method stub
Return o1.getId ()-o2.getId ();
 }
Public String getMethodName ()
 {
Return "forward by id ";
 }

}
Class IdReverseOrder

Package com. jack. SortStrategy;

Import java. util. Comparator;

Public class IdReverseOrder implements Comparator <Person> {
 
@ Override
Public int compare (Person o1, Person o2 ){
// TODO Auto-generated method stub
Return o2.getId ()-o1.getId ();
 }
Public String getMethodName ()
 {
Return "Reverse order by id ";
 }
}
AgeOrder

Package com. jack. SortStrategy;

Import java. util. Comparator;

Public class AgeOrder implements Comparator <Person> {


@ Override
Public int compare (Person o1, Person o2 ){
// TODO Auto-generated method stub
Int result = o1.getAge ()-(o2.getAge ());
If (0 = result) {// if the age is the same, sort by id
Return o1.getId ()-o2.getId ();
  }
Return result;
 }
Public String getMethodName ()
 {
Return "positive by age ";
 }
}
Class AgeReverseOrder

Package com. jack. SortStrategy;

Import java. util. Comparator;

Public class AgeReverseOrder implements Comparator <Person> {
 
@ Override
Public int compare (Person o1, Person o2 ){
// TODO Auto-generated method stub
Int result = o2.getAge ()-(o1.getAge ());
If (0 = result) {// if the age is the same, sort by id
Return o1.getId ()-o2.getId ();
  }
Return result;
 }
Public String getMethodName ()
 {
Return "descending order by age ";
 }
}
Class NameOrder

Package com. jack. SortStrategy;

Import java. util. Comparator;

Public class NameOrder implements Comparator <Person> {

@ Override
Public int compare (Person o1, Person o2 ){
// TODO Auto-generated method stub
Int result = o1.getName (). compareTo (o2.getName ());
If (0 = result) {// if the name is the same, sort by id
Return o1.getId ()-o2.getId ();
  }
Return result;
 }
Public String getMethodName ()
 {
Return "forward by name ";
 }
}
NameReverseOrder

Package com. jack. SortStrategy;

Import java. util. Comparator;

Public class NameReverseOrder implements Comparator <Person> {
@ Override
Public int compare (Person o1, Person o2 ){
// TODO Auto-generated method stub
Int result = o2.getName (). compareTo (o1.getName ());
If (0 = result) {// if the name is the same, sort by id
Return o1.getId ()-o2.getId ();
  }
Return result;
 }
Public String getMethodName ()
 {
Return "Reverse order by name ";
 }
}
Class Client

Package com. jack. SortStrategy;

Import java. util. ArrayList;
Import java. util. Arrays;
Import java. util. Collections;
Import java. util. Comparator;
Import java. util. Iterator;

Public class Client {

/**
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub
ArrayList <Person> personList = new ArrayList <Person> ();
PersonList. add (new Person (1, "zhangsan", 20 ));
PersonList. add (new Person (2, "lisi", 21 ));
PersonList. add (new Person (3, "wangwu", 25 ));
PersonList. add (new Person (4, "zhaoliu", 26 ));
PersonList. add (new Person (5, "chenqi", 28 ));
PersonList. add (new Person (6, "dongba", 10 ));
PersonList. add (new Person (7, "zhansan", 15 ));
PersonList. add (new Person (8, "liujiu", 26 ));

  
/*
* You can use the new Comparator to implement different sorting policies.
* There are
* IdOrder: forward by Id
* IdReverseOrder: Id-based reverse order
* NameOrder: The name is in the forward order.
* NameReverseOrder: name-based reverse order
* AgeOrder: positive chronological order of age
* AgeReverseOrder: age-based reverse order
*/
Comparator <Person> comp = new IdOrder ();

Collections. sort (personList, comp );

System. out. println (IdOrder) comp). getMethodName () + "the sorted sequence is :");
  
System. out. println ("-----------------------");

For (Iterator <Person> itor = personList. iterator (); itor. hasNext ();){
   
Person p = itor. next ();
System. out. println (p. getId () + "" + p. getName () + "" + p. getAge ());
  }

 }

}

Execute the Client to obtain the sorting result.

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.