Design Patterns series (a) - Strategy Mode

concept:   

      Strategy pattern as a software design patterns, refers to the object has a behavior, but in a different scenario, the act has a different algorithm. (Wikipedia)

Understand the concept:

      Concept, said the strategy pattern is a different algorithm behavior in different scenarios. We know that there is a design principle is this: the separation portion changing and unchanging part. In this concept, we can know. The same place, is this behavior, change, implementation of this algorithm is required to conduct, or a strategy.

Scenario:

      This mode of application scenarios should be like this. We need to implement a number can select the most appropriate features we want in. To take a simple example: java Jun, Pascal Jun, Scala Jun three people to go to a restaurant for dinner. But then, the three of them personal taste is not the same, java object-oriented Jun eat dinner, Pascal Jun process-oriented eat dinner, and eat Scala Jun functional dinner, this time assuming you are a restaurant waiter, you give every individual meal time, we should write a

if(pascal君) return 面向过程大餐;else 
if(java君)return 面向对象大餐;else
if(scala君)return 函数式大餐;

That's too bad. Because if Mr. came a spring aop want to eat dinner, it is necessary to change the source code. This is not in line with our "closed for modification, to expand open" principle. Therefore, this design is not enough.

 

The solution:

      We said we separated changing and unchanging things. Change is to be different people on different dishes. We put a little separated from the code. Individually encapsulated. The use of polymorphism, the ability each category a point to some kind of food. We can make everyone realize an Order interface, which defines a la carte this way for everyone to implement this method, then call directly to each person's time to order a la carte approach. So if new people come in, we do not change the original code, just to let new people to realize their order method can be. This would accord with the principles of design. Here is the code.

/*
 * Created by 王镜鑫 on 2016/10/7
 */
interface Order//点餐接口
{
    public void order();//点餐方法
}
class JAVA implements Order//java君实现点餐接口
{
    public void order()
    {
        System.out.println("I want a Object Oriented meal");
    }
}
class Pascal implements Order//Pascal君实现点餐接口
{
    public void order()
    {
        System.out.println("I want a Procedure Oriented meal");
    }
}
class Scala implements Order//Scala君实现点餐接口
{
    public void order()
    {
        System.out.println("I want a functional meal");
    }
}
public class Restaurant//餐厅
{
    private Order order = null;
    public void setOrder(Order order)//设置点餐的人。
    {
        this.order = order;
    }
    public void order()//让点餐人点餐
    {
        order.order();
    }

    public static void main(String[] args)
    {
        Restaurant restaurant = new Restaurant();//实例化一个餐厅
        restaurant.setOrder(new JAVA());//将java君设置进去
        restaurant.order();//让java君点餐
        restaurant.setOrder(new Pascal());//将Pascal君设置进去
        restaurant.order();//让Pascal君点餐
        restaurant.setOrder(new Scala());//将Scala君设置进去
        restaurant.order();//让Scala君点餐
    }
}

Output is as follows:

I want a Object Oriented meal
I want a Procedure Oriented meal
I want a functional meal

Visible, java Jun, Pascal Jun, Scala Jun have to eat their own want to eat dinner. And a compilation of timely again, sir, we are not afraid, you do not modify the original code. Only you need to add a class in the compilation of Mr. ordering interfaces allowed to implement it.

Refining Summary:

      We use an example. To describe the so-called scenarios strategy mode, and how to apply the strategy pattern to solve the problem, make the code easier to expand, reduce coupling. Below we summarize the policy mode.
      By the above example, we know that the strategy pattern contains the following roles:

  •   Context: Context class, play a role in connecting the package, the upper shield direct access to the policy module.
  •   Strategy: Strategy abstract class. Usually an abstract (Abstract classes or interfaces) must be defined for each policy, some methods and properties.
  •   ConcreteStrategy: concrete strategy class, is to achieve specific policy.

The relationship among the following figure:

11-1.png

There is a strategy in the context of property, there is a way to set policies, a working method. Working method is implemented in the working methods of strategy. A specific strategies and specific strategies to implement the strategy B interface, to achieve a work method. In this context the work method calls, method is to call the work actually set specific strategies to achieve the implementation of the strategy and specific strategies decoupling, when there is a new strategy, just need to re-declare a class policy can .
      Strategy Mode is a very simple design pattern, strategy pattern is a package of different algorithms, and algorithms responsibility algorithm itself separated, the algorithm is assigned to a different object management, in one sentence, it is the strategy pattern : family algorithm implemented, and each algorithm are packaged together, they interchanged.
      Strategy mode, which strategy to use is determined by the user, which increases the flexibility of the system, but which to some extent, also increased the difficulty of use of the client. Because the client needs to understand the difference between different algorithm, select the appropriate algorithm. Strategy pattern also reflects the design of such a principle: for interface programming, rather than programming. Our strategy mode, with a representative of the behavior of the interface, multi-state, acts performed in the context of the work, it is a concrete implementation of this interface. We used to think jdk official ranking method. Colloctions.sort (List <T> list) and his overloaded methods sort (List <T> list, Comparator <? Super T> c) their implementation is a direct method calls the sort of List, is the difference between an incoming the comparator is null, is introduced to a specific comparator, the comparator method that is null, the element T list is also achieved Comparablel interface. This is a typical application of the strategy pattern. Reordering, because of the collation classes different needs sorting is not the same, that is, the policy is not the same, so we put the policy package to the client parts, namely the specific needs sorting class, that is, to make the specific needs sorting class implement the Comparable interface, and then passed to the sorting algorithm when sorting algorithms directly call its compareTo method to compare two elements in the order of time, according to the multi-state, his call is actually passed specific compareTo method . Is encapsulated into a specific subclass comparison strategy, can be achieved so that a specific order. This is the application of the strategy pattern in the ordering.
Due to the limited knowledge, there are omissions in the article or the wrong place, welcome to correct me message.

 

Reproduced in: https: //my.oschina.net/u/3023191/blog/1842378

Guess you like

Origin blog.csdn.net/weixin_33671935/article/details/92369139