Design Pattern _ strategy Pattern

Source: Internet
Author: User

Design Pattern _ strategy Pattern
Strategy Pattern

Define a family of algorithms, encapsulate each one, and make them interchangeable. (Define a set of algorithms, encapsulate each algorithm, and enable exchange between them)

 

Context: Context Role Strategy: Policy, algorithm family abstraction, usually interface ConcreteStrategy: specific policy role

 

 

Public interface Strategy {// algorithm of Rule mode public void doSomething ();}
Public class ConcreteStrategy1 implements Strategy {public void doSomething () {System. out. println (algorithm of Policy 1 );}}
Public class ConcreteStrategy2 implements Strategy {public void doSomething () {System. out. println (algorithm of Policy 2 );}}
Public class Context {// abstract policy private Strategy strategy = null; // The constructor sets the specific policy public Context (Strategy _ strategy) {this. strategy = _ strategy;} // The encapsulated policy method public void doAnythinig () {this. strategy. doSomething ();}}

Test

 

 

Public static void main (String [] args) {// declare a specific Strategy strategy = new ConcreteStrategy1 (); // declare the Context object context Context = new Context (Strategy ); // execute the encapsulated method context. doAnythinig ();}

 

With the object-oriented and polymorphism mechanism, algorithms can be switched freely and have better scalability. The disadvantage is that you must first know which policies are in place to decide which strategy to use. This is against the Demeter law.
This is too simple, so there will be no nonsense.

 

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.