Policy mode (instance + Demo) and design mode demo

Source: Internet
Author: User

Policy mode (instance + Demo) and design mode demo

You can understand the following points from this article: 1. Why do you want to write this article? 2. What is the policy mode? 3. Design Principles 4. Implementation of the Policy mode and examples. 5. Advantages and disadvantages of the Policy mode. 6. Miscellaneous

1. Why should I write this article?

In short, there are four words: Record Sharing. It is used to record the information for quick review and sharing of the information learned by others for reference.

2. What is the policy mode?

This will be explained at the end of the article. After reading the examples, I believe you will be more impressed with the definition.

3. Design Principles:

There are a lot of design principles. Here we will talk about what is used in the policy mode. refer to the examples to find out which are useful in the following design patterns:
1. encapsulate changes (identify potential changes in the application and separate them from those that do not need to be changed .)
2. Programming for interfaces and superclasses, rather than for implementation.
3. Multi-Purpose Combination and less inheritance.

4. Implementation and example of the policy mode:

Suppose we are currently developing a game product similar to a Plants vs. botnets. The product manager told us that all botnets must be mobile and attack-able, you can differentiate the appearance.
This is okay. Write an abstract class Character and let all roles (botnets) inherit this class. So Easy.

Abstract class

public abstract class Character {    void move(){        System.err.println("move");    }    void attack(){        System.err.println("attack");    }    abstract void display();}
Public class RedHeadZombie extends Character {// redheaded zombie @ Override void display () {System. err. println ("My head is Red ");}}

Green head botnets:

public class GreenHeadZombie extends Character {    @Override    void display() {        System.err.println("My head is Green");    }}

The product manager came over and told me that we need to set a forward speed for every zombie, and the speed should be different, not all botnets are the same. Well, it's easy to set the speed. I added a speed method to the abstract class so that both red-headed botnets and green-headed botnets can implement this method separately. It's not hard to do either.

Public abstract class Character {// abstract class ...... Abstract void speed ();}
Public class GreenHeadZombie extends Character {// green head zombie ...... @ Override void speed () {System. err. println ("speed is 1.0 ");}}
Public class RedHeadZombie extends Character {// red-headed zombie ...... @ Override void speed () {System. err. println ("speed is 3.0 ");}}

Okay, the speed is enough. If you submit the code, the product manager will come and tell you that the botnet attack methods cannot be the same, how can you make all botnets attack in the same way. It seems a bit reasonable, so I will change it. I can't rewrite all the attack methods.

Public class RedHeadZombie extends Character {// red-headed zombie ...... @ Override void attack () {System. err. println ("RedHeadZombie's attack ");}}
Public class GreenHeadZombie extends Character {// green head zombie ...... @ Override void attack () {System. err. println ("GreenHeadZombie's attack ");}}

After modification, the attack methods are different.

At this time, I secretly glanced at the product manager and found that the product was listening to the song with the legs of Erlang! In my heart, I glanced at him, and then my eyes were on him. Then he slowly put down his delicate leg and came to me ...... 10 thousand words are omitted here. The final result is that he felt that two more botnets (short-legged botnets, non-attacking botnets) need to be added. These botnets are slow but can be remotely attacked, no attack BOT (I don't know what it is for, maybe it's a logistics force that ships weapons to other botnets ). It can be moved but cannot be attacked. Write it again. Continue to write two classes: ShortLegZombie (short leg) and NoAttackZombie (no attack) inherited from Character.

Public class implements legzombie extends Character {// botnets @ Override void display () {System. err. println ("I'm running legzombie");} @ Override void speed () {System. err. println ("speed is slow") ;}@ Override void attack () {System. err. println ("ShortLegZombie's attack ");}}
Public class NoAttackZombie extends Character {// No attack bot @ Override void display () {System. err. println ("I'm NoAttackZombie");} @ Override void speed () {System. err. println ("speed is 5.0");} @ Override void attack () {// nothing to do }}

It's okay. It's not too slow. Done.

Later, the product manager came over and told me that we had just held a meeting. Our final decision was that you would add more botnets to increase the playability of the game and enrich the interface, it's hard for you to improve user availability. You have recently worked overtime. Well, let's take a look at the 40 s.

// Okay. I write it. Can I write it ?...... More than 40 botnets inherit Character to rewrite different diaplay (), speed (), attack () methods. (There are other changes to this botnet category. First, let's write two. I'll see how to change it when you need it !)

Several botnets are added. Let's take a look at the product. The product looked at it with slight eyes and frowned: You can't do it. How can you keep the speed of this zombie? When you encounter an obstacle, it must be slowed down. If there is no obstacle, it must be accelerated. This should be modified. Botnets should not have any attack methods at the starting line. You need to modify the attack methods. It seems reasonable to say that when a botnet meets a certain condition, it modifies the speed and attack mode. Now I have created more than a dozen botnets. It takes a lot of effort to modify them! And dozens of them are not written!

Can you optimize the code so that you can use a few lines of code to create a zombie class? You can modify the status at any time.

In this way, we will rewrite the thought: We will write an abstract class (Character) so that all botnets can inherit this class. The speed and attack methods can be dynamically changed. We will extract the parts that need dynamic changes. We compile two interfaces, ISpeedBehavior and IAttackBehavior, respectively, to extract all the speed and attack behavior. Three types of speed and attack are currently written:

Next we will reorganize our code:

Abstract class Character and subclass

Public abstract class Character {// abstract class public IAttackBehavior mIAttackBehavior; public ISpeedBehavior mISpeedBehavior; void move () {System. err. println ("move");} void attack () {mIAttackBehavior. attack ();} void speed () {mISpeedBehavior. speed ();} public void Behavior (IAttackBehavior) {mIAttackBehavior = IAttackBehavior;} public void Behavior (publish behavior) {mISpeedBehavior = behavior;} abstract void display ();}
Public class RedHeadZombie extends Character {// red-headed zombie public RedHeadZombie (IAttackBehavior behavior, invalid behavior) {mIAttackBehavior = iAttackBehavior; identifier = identifier ;}@ Override void display () {System. err. println ("My head is Red ");}}

......

Attack behavior class interface: IAttackBehavior and implementation class

public interface IAttackBehavior {    void attack();}
public class OrdinaryAttack implements IAttackBehavior {    @Override    public void attack() {        System.err.println("I use ordinary attack");    }}

......

Speed Interface ISpeedBehavior and its subclass:

public interface ISpeedBehavior {    void speed();}
public class NormalSpeed implements ISpeedBehavior{    @Override    public void speed() {        System.err.println("My speed is Normal!");    }}

......

The final dynamic modification speed and attack operations:

/*** Policy mode */public class StrategyActivity extends AppCompatActivity {@ BindView (R. id. zombie_ TV) TextView mZombieTv; @ BindView (R. id. speed_ TV) TextView mSpeedTv; @ BindView (R. id. attack_ TV) TextView mAttackTv; private Character mCharacter; private IAttackBehavior mIAttackBehavior; private limit mISpeedBehavior; private int Limit = 0; private int Limit = 0; private int Limit = 0; private Random mRandom; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_strategy); ButterKnife. bind (this); // default value: mIAttackBehavior = new OrdinaryAttack (); mISpeedBehavior = new NormalSpeed (); mCharacter = new RedHeadZombie (mIAttackBehavior, mISpeedBehavior ); mRandom = new Random () ;}@ OnClick ({R. id. btn_change_zombie, R. id. btn_change_speed, R. id. btn_change_attack}) public void onViewClicked (View view) {switch (view. getId () {case R. id. btn_change_zombie: mRandomZombieNum = mRandom. nextInt (4); switch (mRandomZombieNum) {case 0: mCharacter = new RedHeadZombie (mIAttackBehavior, mISpeedBehavior); mZombieTv. setText ("red-headed botnets"); break; case 1: mCharacter = new GreenHeadZombie (mIAttackBehavior, mISpeedBehavior); mZombieTv. setText ("green head botnets"); break; case 2: mCharacter = new ShortLegZombie (mIAttackBehavior, mISpeedBehavior); mZombieTv. setText ("botnets"); break; case 3: mCharacter = new NoAttackZombie (mIAttackBehavior, mISpeedBehavior); mZombieTv. setText ("no attack bot"); break;} mCharacter. attack (); mCharacter. speed (); break; case R. id. btn_change_speed: mRandomSpeedNum = mRandom. nextInt (3); switch (mRandomSpeedNum) {case 0: mISpeedBehavior = new NormalSpeed (); mSpeedTv. setText ("My speed is normal"); break; case 1: mISpeedBehavior = new SlowSpeed (); mSpeedTv. setText ("My speed is slow"); break; case 2: mISpeedBehavior = new FastSpeed (); mSpeedTv. setText ("My speed is fast"); break;} mCharacter. setISpeedBehavior (mISpeedBehavior); mCharacter. speed (); break; case R. id. btn_change_attack: mRandomAttackNum = mRandom. nextInt (3); switch (mRandomAttackNum) {case 0: mIAttackBehavior = new OrdinaryAttack (); mAttackTv. setText ("I use ordinary rtdinary attack"); break; case 1: mIAttackBehavior = new ReinforceAttack (); mAttackTv. setText ("I use ordinary reinforce attack"); break; case 2: mIAttackBehavior = new SuperAttack (); mAttackTv. setText ("I use ordinary super attack"); break; case 3: break;} mCharacter. setIAttackBehavior (mIAttackBehavior); mCharacter. attack (); break ;}}}

This is OK. You can add a role and modify the speed and attack status at will. I can modify the speed and attack status at any time.

:

Now, what is the rule mode? Yes, the above instances use the policy mode, respectively, to encapsulate the changed parts of the program so that they can replace each other (speed and attack behavior ). That is to say, the policy mode allows the algorithm to change independently of the customers who use the algorithm.

5. Advantages and Disadvantages of policy Mode

Either mode has its own advantages and disadvantages. Of course, each time we write code, we need to consider its advantages and disadvantages.
Advantages of the Policy mode:
1. provides a way to quickly replace inheritance relationships: in this case, we can quickly replace botnets, speed, and attack types.
2. Reduce if else and other judgment statements in the Code: we do not need to judge when changing the Attack Status. When a condition is reached, we can directly switch the attack implementation class. For example, the preceding general attack becomes a super attack.
3. Implementation options: the Policy mode provides different implementations.
Disadvantages of Rule mode:
1. The policy mode will cause many policy categories: All speed implementation classes and attack implementation classes mentioned above ......
2. High communication overhead: for example, the speed of the above speed interface must pass three parameters. These three parameters are meaningful to some botnets and meaningless to most botnets. In this case, unnecessary communication overhead will occur.
3. Do you have to know the differences between all implementation classes? Every time you create a zombie class, you must know the differences between all the speed classes and attack implementation classes. In this case, specific implementation problems are exposed. Therefore, you must use the policy mode only when the behavior class is related to the role behavior.

6. Summary

Now let's review the three design principles used in the policy model that we just mentioned:
1. encapsulation changes. We encapsulate the changing speed and attack behavior for Dynamic Change calls.
2. For interfaces and super-class programming, not for implementation programming. We use the ISpeedBehavior and IAttackBehavior interfaces to represent the speed and attack behavior. Each specific behavior implements one of the interfaces.
3. Multi-Purpose Combination and less inheritance. The biggest benefit of combination is elasticity, which greatly facilitates code maintenance and demand modification. At the beginning, we used the inheritance method. When a large number of zombie classes are added, the Code maintenance and modification workload will be very large. After optimization, we will use a combination of speed and attack and botnet to write code.

In fact, the policy mode is often used in game development. For example, the arcade game server has different roles, such as pig, Bai longma, and Sun Wukong. They all have weapons. They may be destroyed by monsters and can be picked up by themselves. You can also send different methods. Of course, this will not write code, but it will focus on the train of thought.

 

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.