Design Mode - Behavioral - Strategy Pattern

Strategy Mode (Strategy):

  Strategy Mode is a package of algorithms, and algorithms use is the responsibility of segmentation algorithm itself off, delegated to different objects management. Strategy pattern usually a series of algorithms to package a series of strategies inside the class, as an abstract policy subclasses. One sentence, that is: "preparing a set of algorithms, each algorithm and encapsulated, so that they are interchangeable."

Strategy Role model:  

  

  1) Environmental (Context): or using a combination of polymeric way to maintain a reference to the object Strategy.

  2) Abstract Strategy (Strategy): the definition of a common interface for all supported algorithms. Context use this interface to invoke a ConcreteStrategy defined algorithms.

  3) Specific Strategy (ConcreteStrategy): implement Strategy interface.

Case:

  A charge store sales system uses three logic: normal fees; cashback charge (at least 300 back to 20); fee discounts (20% off). 

 1 internal class Program
 2 {
 3     private static void Main(string[] args)
 4     {
 5         CashContext cashContext = new CashContext(new CashNormal());
 6         Console.WriteLine(cashContext.GetResult(200));
 7         CashContext cashContext2 = new CashContext(new CashRebate(0.8));
 8         Console.WriteLine(cashContext2.GetResult(200));
 9         CashContext cashContext3 = new CashContext(new CashReturn(300, 20));
10         Console.WriteLine(cashContext3.GetResult(300));
11     }
12 }
13 
14 /// <summary>
15 /// 环境类Context
16 /// </summary>
17 public class CashContext
18 {
19     private CashSuper cs;
20 
21     public CashContext(CashSuper cashSuper)
22     {
23 is          the this .cs = cashSuper;
 24      }
 25  
26 is      public  Double GetResult ( Double Money)
 27      {
 28          IF (CS =! Null )
 29          {
 30              return cs.AcceptCash (Money);
 31 is          }
 32          return  0 ;
 33 is      }
 34 is  }
 35  
36  ///  <Summary> 
37 [  /// charging system, corresponds Strategy
 38 is  ///  </ Summary> 
39  public interface CashSuper
40 {
41     double AcceptCash(double money);
42 }
43 
44 /// <summary>
45 /// 正常收费
46 /// </summary>
47 public class CashNormal : CashSuper
48 {
49     public double AcceptCash(double money)
50     {
51         return money;
52     }
53 }
54 
55 /// <summary>
56 /// 打折收费
 57  ///  </ summary> 
58  public  class CashRebate: CashSuper
 59  {
 60      private  double moneyRebate = 1d;
61  
62      public CashRebate ( double moneyRebate)
 63      {
 64          this .moneyRebate = moneyRebate;
65      }
 66  
67      public  double AcceptCash ( double money)
 68      {
 69          return money * moneyRebate;
70     }
71 }
72 
73 /// <summary>
74 /// 返现收费
75 /// </summary>
76 public class CashReturn : CashSuper
77 {
78     private double moneyCondition = 0.0d;
79     private double moneyReturn = 0.0d;
80 
81     public CashReturn(double moneyCondition, double moneyReturn)
82     {
83         this.moneyCondition = moneyCondition;
84         this.moneyReturn = moneyReturn;
85     }
86 
87     public double AcceptCash(double money)
88     {
89         double result = money;
90         if (money >= moneyCondition)
91             result = money - Math.Floor(money / moneyCondition) * moneyReturn;
92         return result;
93     }
94 }

Strategy mode advantages and disadvantages:

  advantage:

    1) Strategy Mode provides a family of related management algorithm approach. Class hierarchy strategy defines a family of algorithms or behavior. Proper use inheritance code can be transferred to a common parent class, so as to avoid duplication of code.

    2) Strategy Mode can provide a way to replace inheritance. Inheritance can handle a variety of algorithms or behaviors. If not, use the Strategy pattern, then use the algorithm or behavior on the kind of environment there may be some sub-categories, each sub-class provides a different algorithm or behavior. However, this way the user algorithm or algorithms and behavior on the act itself or mixed together. Which algorithm or logic decide what kind of action to take on the behavior of the algorithm or logic and mixed together, making it impossible to re-evolved independently. Inheritance allows dynamically change the algorithm or behavior becomes impossible.

    3) use the strategy pattern to avoid the use of multiple conditional branch statement. Multi-branch statement is not easy to maintain, take it to an algorithm which logic and arithmetic or logic or behavior which take an act of mixing together, all listed in a multi-branch statement inside, but also inherited primitive and backward than the way .

  Disadvantages:

    1) The client must know all the policy class, and the class to decide which strategy to use. This means that the client must understand the difference between these algorithms, in order to timely select the appropriate algorithm class. In other words, the policy applies only to model the client know the situation all the algorithms or behavior.

    2) Strategy Mode cause a lot of strategy classes, each class will have specific strategies a new class. It can sometimes depend on the environment by storing the client state in the inside, and the Strategy designed to be shared, so that strategies can be used class instance different clients. In other words, you may be used Flyweight to reduce the number of objects.

Strategy mode of application scenarios:

  1) a system need to dynamically select several algorithms when one of each can be encapsulated into the algorithm class policy.

  2) class defines a plurality of behavior and these behaviors in the form of a plurality of conditional statements in the operation of this class, each conditional branch may be moved into their respective policy class in place of the conditional statements.

  Each algorithm 3) the system completely independent of each other, and when the customer hide implementation details of the specific algorithm requirements.

  4) The system requires customers to use the algorithm should not know when the data in its operations, strategy pattern can be used to hide data structure associated with the algorithm.

  5) multiple classes only difference in the performance of different behavior, you can use the Strategy pattern, behavior at runtime dynamically select specific to perform.

Strategy pattern and factory pattern difference?

  From a structural point of view, the policy model and factory pattern is a subclass inherits the abstract parent class, by passing parameters to the containers (Factory class factory mode, the Content-based strategy mode), selects the corresponding operation behavior classes. But we all know that the factory model is to create a design pattern, while strategy pattern is a behavioral design patterns. That both in the end what difference does it make?

  1) factory pattern is used to create objects, the Strategy pattern is to allow an object to choose a behavior in a number of behavior.

  2) concerns are not the same, to create an object of a concern, a concern is the behavior of the package.

  3) solve different problems: the factory pattern is a creational design pattern, it accepts commands, make a new instance to meet the requirements; it is the main solution is uniform distribution of resources, will create the object is completely independent, so that to create an object and specific use client-independent. Mainly used in multi-database selection, file loading libraries and so on. Strategy pattern is to solve is to switch and expansion strategy, said to be more concise definition of family policy were encapsulated, so that they can replace each other, so that changes in the strategy pattern strategy is independent of the customer usage policies.

  4) corresponds to a black box facility, a policy corresponding to a white box.

Strategy mode and bridge mode difference?

  In bridge mode, Abstraction Implementor cited by way of polymerization. Strategy mode, Context also use aggregated reference Strategy abstract interface. As can be seen from the structure of FIG both, in both modes, there is an object reference in the case of using a polymerization abstract interface to another object, and implement the abstract interface may be various and may be replaced. It can be said decoupling between both called on the appearance of those being the caller, as well as separation of interface from implementation of the abstract. But there are some differences between the two:

  1) in the form, not only in the bridge mode change has Implementor (ConcreateImplementior), but may be changed Abstraction (RefinedAbstraction), and between the changes are completely independent, and the loose coupling between RefinedAbstraction ConcreateImplementior, they merely by Abstraction link and relationship between Implementor. In strategy mode, does not consider changes in Context, only algorithms irreplaceable.

  2) semantically, bridging model emphasizes Implementor interface provides only basic operations, and Abstraction these basic operational definition is based on a higher level of operation. Strategy and tactics model emphasizes the abstract interface provided is an algorithm, typically stateless, no data, and Context is simply call these algorithms to complete its operation.

  3) bridge mode only defines Abstraction Implementor interface and interface definitions, Abstraction Implementor interface to communicate with not only to exist, which reflects the structural characteristic pattern: through inheritance, polymerized combination of classes and objects to form a larger structure. In strategy mode, Startegy and Context interface is the interface collaboration between the two, did not relate to other function interface, so it is a pattern of behavior. The main features of behavior patterns that deals with communication between objects, often by introducing an intermediary object will decouple communication parties, here is actually the Context actual algorithm provider decoupling.

  所以相对策略模式,桥接模式要表达的内容要更多,结构也更加复杂。桥接模式表达的主要意义其实是接口隔离的原则,即把本质上并不内聚的两种体系区别开来,使得它们可以松散的组合,而策略在解耦上还仅仅是某一个算法的层次,没有到体系这一层次。从结构图中可以看到,策略的结构是包容在桥接结构中的,桥接中必然存在着策略模式,Abstraction与Implementor之间就可以认为是策略模式,但是桥接模式一般Implementor将提供一系列的成体系的操作,而且Implementor是具有状态和数据的静态结构。而且桥接模式Abstraction也可以独立变化。

参考:https://blog.csdn.net/donnie88888888/article/details/52751328

  https://blog.csdn.net/basycia/article/details/50478245

  http://www.blogjava.net/wangle/archive/2007/04/25/113545.html

Guess you like

Origin www.cnblogs.com/az4215/p/11617422.html