English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This article describes an example of Android programming design pattern - Strategy Pattern. Share it with everyone for reference, as follows:
1. Introduction
In software development, we often encounter such situations: to implement a certain function, there can be multiple algorithms or strategies, and we choose different algorithms or strategies according to the actual situation to complete the function. For example, sorting algorithms can use insertion sort, merge sort, bubble sort, and so on.
For this situation, a conventional method is to write multiple algorithms in one class. For example, if multiple sorting algorithms need to be provided, these algorithms can be written into one class, with each method corresponding to a specific sorting algorithm: of course, these sorting algorithms can also be encapsulated in a unified method, and specific algorithms are selected through conditional judgment statements such as if...else... or case. Both of these implementation methods can be called hard coding. However, when many algorithms are concentrated in one class, the class becomes bloated, the maintenance cost of the class increases, and it is easier to cause errors during maintenance. If we need to add a new sorting algorithm, we need to modify the source code of the encapsulated algorithm class. This clearly violates the OCP principle and the Single Responsibility Principle.
If these algorithms or strategies are abstracted out and a unified interface is provided, different algorithms or strategies have different implementation classes. In this way, different implementation objects can be injected into the program client to dynamically replace algorithms or strategies, which makes the mode more scalable and maintainable, that is, the strategy pattern we will talk about in this section.
In simple terms, if a problem has multiple solutions, the simplest is to use if-else or switch-The case method selects different solutions according to different scenarios, but this has too high coupling, bulky code, and difficult to maintain. At this time, the strategy pattern can be used to solve it.
2. Definition
The strategy pattern defines a series of algorithms, encapsulates each algorithm, and allows them to be interchanged. The strategy pattern makes the algorithm independent of the client that uses it and changes independently.
3. Use Cases
For multiple ways to deal with the same type of problem, there are only differences in specific behavior
Need to safely encapsulate multiple operations of the same type
There are multiple subclasses of the same abstract class, and if you need to use if-else or switch-case to select a specific subclass
4. UML Class Diagram of the Strategy Pattern
UML Class Diagram:
Context: Used to operate the strategy's context environment.
Stragety: The abstract of the strategy.
ConcreteStrategyA, ConcreteStrategyB: Specific strategy implementation.
5. Simple Implementation
Requirement: Calculate the book price, basic members have no discount, intermediate members get a discount of9discount, senior members get a discount of8discount. If the general writing method, it should be if-else judgment what level of member they are, and calculate the corresponding discount. Below, we use the strategy pattern to implement it.
Abstract Discount Class:
public interface MemberStrategy { /** * Calculate the price of the book * @param booksPrice The original price of the book * @return Calculate the discounted price */ public double calcPrice(double booksPrice); }
Basic Member Discount Class:
public class PrimaryMemberStrategy implements MemberStrategy{ /** * Basic Member Discount */ @Override public double calcPrice(double booksPrice) { System.out.println("There is no discount for basic members"); return booksPrice; } }
Intermediate Member Discount Class:
public class IntermediateMemberStrategy implements MemberStrategy{ /** * Intermediate Member Discount */ @Override public double calcPrice(double booksPrice) { System.out.println("The discount for intermediate members is ",10%"); return booksPrice * 0.9; } }
Senior Member Discount Class:
public class AdvancedMemberStrategy implements MemberStrategy{ /** * Senior Member Discount */ @Override public double calcPrice(double booksPrice) { System.out.println("The discount for senior members is")20%")); return booksPrice * 0.8; } }
Price class:
public class Price { //Holds a specific strategy object private MemberStrategy strategy; /** * Constructor, passing a specific strategy object * @param strategy Specific strategy object */ public Price(MemberStrategy strategy){ this.strategy = strategy; } /** * Calculate the price of the book * @param booksPrice The original price of the book * @return Calculate the discounted price */ public double quote(double booksPrice){ return this.strategy.calcPrice(booksPrice); } }
Client:
public class Client { public static void main(String[] args) { //Select and create the strategy object to be used MemberStrategy strategy1 = new AdvancedMemberStrategy(); //Create environment Price price = new Price(strategy1); //Calculate price double quote = price.quote(300); System.out.println("The final price of the book is:") + quote); } }
Result:
The discount for senior members is20% The final price of the book is:240.0
Six, the difference between strategy pattern and factory pattern
Factory pattern | Strategy pattern |
---|---|
Creational design patterns | Behavioral design patterns |
Focus on object creation | Focus on the choice of behavior |
Black box (no need to know the specific implementation process) | White box (knows the specific implementation process) |
Seven, the implementation of the strategy pattern in Android source code
With the development of technology, engineers have been paying more and more attention to user experience and user interaction. Therefore, animation has become an indispensable part of many applications. Even a simple guide page needs to be made into an animated effect, and the hiding of a button also needs to be added with fade-in and fade-out animation effects. The principle of animation implementation is to quickly switch the screen in a short period of time, and the frequency of this switch needs to reach a level where the human eye cannot feel any lag, for example, the standard movie is24frames/Seconds. When the animation is smooth on Android, it can reach60 frames/Seconds, the human eye can basically not see the interval, so, when we see this animation, it is very smooth.
单纯是动画还不足以满足我们的需求,在动画执行的过程中,我们还需要一些动态效果,这有点类似于电影的慢镜头,有时候我们需要它慢一点,有时候需要快一点,这样动画也变得灵动起来。这些动态效果就是通过插值器(TimeInterpolator)实现的,我们只需要对Animation对象设置不同的插值器就可以实现不同的动态效果。
LinearInterpolator, AccelerateInterpolator, CycleInterpolator, etc., implement Interpolator, obtain the current time percentage through getInterpolator(float input), and calculate the attribute value of the animation accordingly.
8. Summary
The strategy pattern is mainly used to separate algorithms, with different specific implementation strategies under the same behavior abstraction. This pattern well demonstrates the open-closed principle, that is, define abstraction, inject different implementations, and achieve good scalability.
Advantages:
The structure is clear and straightforward, and it is simple and intuitive to use.
The degree of coupling is relatively low, and it is convenient to expand.
Operation encapsulation is more thorough and data is more secure.
Disadvantages:
With the increase of strategies, subclasses will also become more numerous.
Readers who are interested in more content related to Android can check the special topics on this website: 'Android Development入门与进阶教程', 'Android Debugging Skills and Common Problem Solving Methods Summary', 'Summary of Android Basic Component Usage', 'Summary of Android View View Skills', 'Summary of Android Layout Layout Skills', and 'Summary of Android Widget Usage'.
I hope the content described in this article will be helpful to everyone in Android program design.
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please replace '#' with '@' when sending an email for reporting. Provide relevant evidence, and once verified, the website will immediately delete the content suspected of infringement.