JAVA design mode policy mode

Source: Internet
Author: User

Use

Policy mode (strategy) It defines the algorithm family, which is encapsulated separately so that they can be replaced with each other, and this pattern allows the algorithm to change without affecting the client using the algorithm.

The policy pattern is a behavioral pattern .

structure

Figure-Strategy mode structure diagram

Strategy: Defines the public interface (ALGORITHMINTERFACE) for all algorithms. The context uses this interface to invoke the specific algorithm defined by Concretestrategy.AbstractclassStrategy {
PublicAbstractvoidAlgorithminterface ();
}

Concretestrategy : Implements the Algorithm interface (ALGORITHMINTERFACE) in the strategy.

classConcretestrategyaextendsStrategy {
@Override
PublicvoidAlgorithminterface () {
SYSTEM.OUT.PRINTLN ("algorithm a");
}
}

classConcretestrategybextendsStrategy {
@Override
PublicvoidAlgorithminterface () {
SYSTEM.OUT.PRINTLN ("algorithm B");
}
}

classConcretestrategycextendsStrategy {
@Override
PublicvoidAlgorithminterface () {
SYSTEM.OUT.PRINTLN ("Algorithm C");
}
}

Context : Configured with a concretestrategy. Maintains a reference to the Strategy object.

classContext {
Strategy strategy;
PublicContext (Strategy strategy) {
This. strategy = strategy;
}

PublicvoidContextinterface () {
Strategy. Algorithminterface ();
}
}

Test code

Public classStrategypattern {
PublicStaticvoidMain (string[] args) {
Context Context1 =NewContext (NewConcretestrategya ());
Context1. Contextinterface ();

Context context2 =NewContext (NewConcretestrategyb ());
Context2. Contextinterface ();

Context CONTEXT3 =NewContext (NewCONCRETESTRATEGYC ());
Context3. Contextinterface ();
}
}View Code

Run results

Algorithm A
Algorithm B
Algorithm CView Code

JAVA design mode policy mode

Related Article

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.