Design mode policy mode with role play as background

Source: Internet
Author: User
Tags what interface

Today do not want to write code, to bring you a design pattern of the article, to help you can organize the system into easy to understand, easy to maintain, resilient architecture.

Let's take a look at the definition of the strategy pattern:

Policy mode (strategy pattern): Defines the algorithm family, encapsulates each other, so that they can be replaced with each other, this pattern allows the algorithm to change independently of the customers using the algorithm.

Well, for the definition, certainly not a glance can see, otherwise this article will end, for everyone to simply sweep a glance, know a general, and then continue to read the following article, read after the aftertaste, the effect of Bang Crisp. Everyone should have played the role of martial arts game, the following I will play a role in the background, for you to introduce: Suppose the company needs to do a martial arts game, we are responsible for the role of the game module, the need is this: each role corresponds to a name, each type of role corresponding to a look, each character has a flight, attack, defensive skills

The initial code:

Package Com.zhy.bean;/** * The role of the game Super class * * @author Zhy **/ Public Abstract classrole{protectedString name; protected Abstract voiddisplay (); protected Abstract voidrun (); protected Abstract voidattack (); protected Abstract voiddefend ();}
Package Com.zhy.bean; Public classRolea extends role{ PublicRolea (String name) { This. Name =name; } @Overrideprotected voiddisplay () {System. out. println ("Look 1"); } @Overrideprotected voidrun () {System. out. println ("Jinchantuoqiao"); } @Overrideprotected voidattack () {System. out. println ("Dragon 18 Palm"); } @Overrideprotected voiddefend () {System. out. println ("Iron Head!"); }}

Not a few minutes, you wrote the above code, feel that has fully played the OO thought, is stealing the joy, this time the project manager said, add two more characters

Roleb (appearance 2, Dragon 18 Palm, iron cloth shirt, jinchantuoqiao).

Rolec (looks 1, has nine Yang Martial, iron cloth shirt, smoke bomb).

So you feel no problem, start writing code, continue to integrate role, write the following code:

Package Com.zhy.bean; Public classRoleb extends role{ PublicRoleb (String name) { This. Name =name; } @Overrideprotected voiddisplay () {System. out. println ("Look 2"); } @Overrideprotected voidrun () {System. out. println ("Jinchantuoqiao");//Copy from Rolea} @Overrideprotected voidattack () {System. out. println ("Dragon 18 Palm");//Copy from Rolea} @Overrideprotected voiddefend () {System. out. println ("Iron Cloth Shirt"); }}
Package Com.zhy.bean; Public classRolec extends role{ PublicRolec (String name) { This. Name =name; } @Overrideprotected voiddisplay () {System. out. println ("Look 1");//Copy from Rolea} @Overrideprotected voidrun () {System. out. println ("Smoke Bombs"); } @Overrideprotected voidattack () {System. out. println ("Nine Yang Martial"); } @Overrideprotected voiddefend () {System. out. println ("Iron Cloth Shirt");//Copy from B    }}

When you're done, you don't seem to be as confident as you were, and you find that there are quite a lot of duplicated code in the code, and you need to consider re-architecting the architecture. So you want to, or each skill is written into the interface, what skills of the role of what interface, a simple thought, think this idea tall ah, but realize it will find that the interface does not implement code reuse, each implementation of the interface class, or must write their own write implementation. So, we need change! Follow the principles of design, identify parts of your application that may need to change, separate them, and don't mix with code that doesn't need to change. We find that the display,attack,defend,run of each character is likely to change, so we have to write it out independently. Based on another design principle: Programming for an interface (super-type), rather than implementing programming, we transform the code into this:

Package Com.zhy.bean;  Public Interface iattackbehavior{    void  attack ();}
Package Com.zhy.bean;  Public Interface idefendbehavior{    void  defend ();}
Package Com.zhy.bean;  Public Interface idisplaybehavior{    void  display ();}
 package Com.zhy.bean;  public  class   Attackjy implements iattackbehavior{@Override   void   attack () {System.  out . println ( "  nine Yang Martial!      ); }}
 package Com.zhy.bean;  public  class   Defendtbs implements idefendbehavior{@Override  public  void   defend () {System.  out . println ( "  Iron shirt   "    ); }}
Package Com.zhy.bean;  Public class RUNJCTQ implements irunbehavior{    @Override    publicvoid  run ()    {        System. out. println (" jinchantuoqiao ");}    }

This is where you need to change the role code:

Package Com.zhy.bean;/** * The role of the game Super class * * @author Zhy **/ Public Abstract classrole{protectedString name; protectedIdefendbehavior Defendbehavior; protectedIdisplaybehavior Displaybehavior; protectedIrunbehavior Runbehavior; protectedIattackbehavior Attackbehavior;  PublicRole Setdefendbehavior (Idefendbehavior defendbehavior) { This. Defendbehavior =Defendbehavior; return  This; }     PublicRole Setdisplaybehavior (Idisplaybehavior displaybehavior) { This. Displaybehavior =Displaybehavior; return  This; }     PublicRole Setrunbehavior (Irunbehavior runbehavior) { This. Runbehavior =Runbehavior; return  This; }     PublicRole Setattackbehavior (Iattackbehavior attackbehavior) { This. Attackbehavior =Attackbehavior; return  This; }    protected voiddisplay () {displaybehavior.display (); }    protected voidrun () {runbehavior.run (); }    protected voidattack () {attackbehavior.attack (); }    protected voiddefend () {defendbehavior.defend (); }}

Each role now requires only one name:

Package Com.zhy.bean;  Public class Rolea extends role{    public  Rolea (String name)    {        this. Name=  Name;}    }

Now we need a Jinchantuoqiao, the Dragon 18 Palm! , the iron shirt, looks like the 1 role a only needs this:

Package Com.zhy.bean; Public classtest{ Public Static voidMain (string[] args) {Role Rolea=NewRolea ("A"); Rolea.setattackbehavior (NewATTACKXL ())//. Setdefendbehavior (NewDefendtbs ())//. Setdisplaybehavior (NewDisplaya ())//. Setrunbehavior (NewRUNJCTQ ()); System. out. println (Rolea.name +":");        Rolea.run ();        Rolea.attack ();        Rolea.defend ();    Rolea.display (); }}

After our modification, now all of the skills of the implementation of 100% of the reuse, and casual project managers need what role, for us only need to dynamically set the skills and display, is not perfect. Congratulations, now that you have learned the strategy model, now we go back to the definition, the definition of the algorithm family: In fact, the above example of the skills, the definition of the customer: In fact, is rolea,roleb ... We have defined an algorithm family (various skills) that can be replaced according to requirements, and the implementation of algorithms (various skills) is independent of the customer (role). Now is not a good understanding of the definition of the policy model.

Attach a UML diagram to make it easy for you to understand:

Finally, summarize the principles of OO:

1. Package changes (package the code that may change).

2, multi-use combination, less with inheritance (we use a combination of methods, set up the algorithm for the customer)

3, for the interface programming, not for the implementation (for role class design completely for roles, and the implementation of the skill is not related)

Click here to download the source code

Design mode policy mode with role play as background

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.