Java Design pattern----strategy (policy mode)

Source: Internet
Author: User

Design patterns, a programmer's understanding of design patterns: "Don't understand" why something very simple is so complicated . And then as the experience of software development began to understand what I saw as "complex" is precisely the essence of design patterns,What I understand. "Simple" is the key starts locks model, the purpose is only to focus on solving the present problem, and the design pattern of "complex" is that it is to construct a "master key", the purpose is to propose a lock for all locks scheme. I've been writing "simple" code before I really understood design patterns. This one "Simple" is not a simple function, but a simple design. Simple design means lack of flexibility, the code is hard, it's only useful in this project, and getting the rest of the project is rubbish, which I call "Disposable Code". To make the code reusable, design your code in ' design mode '. Many of the programmers I know have a sense of brief encounter after exposure to design patterns, and some describe that they feel like they have been reborn after learning the design patterns and have reached new heights. Some people even know whether to understand design patterns as a standard for programmers to divide the level. We also cannot fall into the trap of patterns, in order to use the pattern to go to the pattern, that will fall into the formalism. When we use patterns, we must pay attention to the intent of the pattern (intent), rather than focusing too much on the implementation details of the pattern, as these implementation details may change in certain circumstances. Do not stubbornly believe that a class diagram or implementation code in a design pattern represents the pattern itself. design principles: ( important ) 1. The logic code is independent of the method, focusing on encapsulation--easy to read, easy to reuse. Do not write down hundreds of lines of logical code in one method. Separate the small logic code, write in other methods, easy to read its repeatable call. 2. Write the class, write the method, write the function, should consider its portability, reuse sex: Prevent one-time code! Is it possible to get other things in the same category? Can I get it in other systems? 3. Skilled use of the idea of inheritance: to find the application of the same, and not easy to change things, to extract them into the abstract class, let the subclass to inherit them, the idea of inheritance, but also convenient to build their own logic on the results of others. such as ImageField extends JTextField; skilled use of the idea of the interface: Find out where the application may need to change, separate them out, do not mix with the code that does not need to change. to make a very simple thing so complicated, one-time code, design pattern Advantage Example Description: (strategy mode)Description: Simulated duck game application, requirements: The game will appear in a variety of color shapes of ducks, while swimming and playing, while the quack. First Method: (One-time code)Directly write a variety of duck class: mallardduck//Mallard, redheadduck//red duck, all kinds have three methods: Quack (): Method of Swim (): Method of Swimming display (): Method of appearance The second approach: use inherited features to raise the common part and avoid repetitive programming. Namely: Design a duck's superclass (superclass), and let all kinds of ducks inherit this super class.
 class   duck{ public  void  Quack () {//  n  System.out.println ("Quack"  public  void  swim () {//  swim  System.out.println ("Swim"  public  abstract void  display (); /*   */ }  

For its subclasses, simply inherit it and implement your own display () method.
Ducks

 Public class extends duck{     publicvoid  display () {          System.out.println ("Mallard color ...");}   }

Red-headed Duck

 Public class extends duck{     publicvoid  display () {          System.out.println ("Red-headed Duck color ... ");   
Unfortunately, customers are now proposing new demands to let ducks fly. This for our OO programmer, in the simple, in the superclass in the addition of a method can be.
Public Abstract classduck{ Public voidQuack () {//QuackSYSTEM.OUT.PRINTLN ("Quack"); }      Public voidSwim () {//SwimmingSystem.out.println ("Swimming"); }         Public  Abstract voidDisplay ();/*because the appearance is different, let the subclass decide for themselves. */    Public voidFly () {System.out.println ("Fly It!" Duck); }}

For ducks that can't fly, simply cover them in a subclass.
Crippled Duck

 Public class extends duck{     publicvoid  display () {          System.out.println ("The color of the crippled duck ...");     Public void Fly () {    //  

Other flying ducks do not need to be covered.

So all the ducks that inherit this super-class will fly. But the problem came out again, the customer also raised some ducks can fly, some can not fly. >>>>>> Reviews: For the above design, you may find some drawbacks, if the superclass has a new feature, the subclass must be changed, this is what we develop the least like to see, one class changed to another class also changed, which is a bit out of line with OO design. This is obviously coupled together. Take advantage of inheritance--coupling is too high. The third method: Improve with the interface.We extract the parts that are prone to change and encapsulate them to cope with future political reforms. While the amount of code is increasing, usability increases and the coupling is reduced. We extracted the Fly method and quack from the duck.
   Public Interface flyable{      publicvoid  fly ();    Public Interface quackable{     publicvoid  quack ();  }

The final duck design becomes:

Public Abstract class duck{     publicvoid swim () {   // swimming            System.out.println ("swimming" );    }          Public  Abstract void /* because the appearance is different, let the subclass decide for themselves. */}

And Mallardduck,redheadduck,disabledduck can be written as:

Ducks

 Public classMallardduckextendsDuckImplementsflyable,quackable{ Public voiddisplay () {System.out.println ("The color of mallard ..."); }    Public voidFly () {//Implement this method  }    Public voidQuack () {//Implement this method  } }

Red-headed Duck

  Public classRedheadduckextendsDuckImplementsflyable,quackable{ Public voiddisplay () {System.out.println ("The color of the red-headed Duck ..."); }    Public voidFly () {//Implement this method  }    Public voidQuack () {//Implement this method  }} 

The crippled duck only realizes the quackable (can call cannot fly)

 Public class extends Implements quackable{     publicvoid  display () {          System.out.println ("The color of the crippled duck ..." );   }     Public void Quack () {    // Implement the method   }}
>>>>>> review: The benefits: This has been designed so that our programs reduce the coupling between them. Insufficient: flyable and quackable interface at first seems to be quite good, solve the problem (only fly to the duck to achieve flyable), but the Java interface does not have implementation code, so the implementation of the interface can not achieve code reuse. The Fourth method: Summary of the above: Inheritance benefits: Let the common part, can be reused. Avoid repetitive programming. Poor inheritance: high coupling. Once the superclass adds a new method, the subclasses inherit, owning this method, The Kawai class does not implement this method in a significant amount, and is modified in large quantities. when inheriting, subclasses are not allowed to inherit other classes. Interface Benefits: solves the problem of high inheritance coupling. and allows the implementation class to inherit or implement other classes or interfaces. Bad interface: cannot really implement code reuse. The following policy modes can be used to resolve the problem. -------------------------Strategy (Policy mode)-------------------------We have a design principle: to find things that are the same in the application, that are not prone to change, to extract them into abstract classes, to allow subclasses to inherit them, to find out where the application might need to change, to isolate them, and not to mix with the code that doesn't need to change. -->important. Now, in order to separate the "changed and unchanged parts", we are going to create two sets of classes (completely away from the Duck Class), one is "fly" related, the other is "quack" related, each group of classes will implement their respective actions. For example, we may have a class that implements "quack", another class that implements "squeaking", and a class that implements "quiet." First write two interfaces. Flybehavior (flight behavior) and Quackbehavior (called behavior).
 Public Interface flybehavior{     publicvoid  fly ();        Public Interface quackbehavior{     publicvoid  quack ();}

We are defining some specific implementations for Flybehavior.

 Public class Implements flybehavior{    publicvoid  fly () {     //  All winged ducks have been flown.  public classimplements  flybehavior{           Public void   Fly () {      // do Nothing, not fly     }}   

Several specific implementations for Quackbehavior.

 Public classQuackImplementsquackbehavior{ Public voidQuack () {//to achieve a quack duck  }}  Public classSqueakImplementsquackbehavior{ Public voidQuack () {//implement a squeaky duck  }}  Public classMutequackImplementsquackbehavior{ Public voidQuack () {//don't do anything, don't call  }}

Reviews One: This design allows flight and the action of a quack to be reused by other objects, since these actions are not related to the Duck class. And we're adding some new

Behavior, does not affect the existing behavior class, and does not affect the "use" to the flight behavior of the Duck class. Finally, let's see how duck is designed.
Public Abstract classduck{--------->in an abstract class, each interface is declared and the corresponding method is defined for each interface. Flybehavior Flybehavior;//InterfaceQuackbehavior Quackbehavior;//Interface        PublicDuck () {} Public Abstract voiddisplay ();  Public voidswim () {//The realization of swimming behavior        }        Public voidPerformfly () {flybehavior.fly (); //-because it is an interface, the corresponding method is called according to the way the inheriting class implements it. } Public voidPerformquack () {quackbehavior.quack ();
} }

See how Mallardduck is implemented.
-----> through the construction method, generate ' fly ', ' call ' the concrete implementation of the class instance, thus specifying the ' fly ', ' called ' specific properties

 Public class extends duck{       public  mallardduck {               new  flywithwings ();         New Quack ();        // because Mallardduck inherits the duck, all have flybehavior and Quackbehavior instance variables}     Public void display () {     // implementation    }}

This is enough to be able to fly, but also can be called, at the same time to show their own color.

Such a design we can see is the Flybehavior, quackbehavior the instantiation of the sub-class is written.   We can also make a dynamic decision. We just need to add two methods to the duck.The difference between assigning a property to a setter in a constructor method and using a property:The property is assigned in the construction method: fixed, immutable;with the property setter, can be instantiated after the object, dynamic changes, more flexible.
 class   duck{Flybehavior Flybehavior;  //       interface  Quackbehavior Quackbehavior; //       interface  public  void   Setflybehavior (Flybehavior flybehavior) { th     is . Flybehavior = Flybehavior;  public  void   Setquackbehavior (Quackbehavior quackbehavior { this . Quackbehavio     R= Quackbehavior; } }

This article is from "Changes we need!" blog, be sure to keep this source http://shenzhenchufa.blog.51cto.com/730213/161581

Java Design pattern----strategy (policy mode)

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.