Strategy Pattern
Design patterns are commonly used patterns in software development, but in fact many people only understand their concepts and do not know how to apply them in actual development. Therefore, we can explain the strategy model in detail based on actual development cases.
If you have any questions, are dissatisfied with the article, find errors or have a better way, please feel free to submit them in a comment, private message or email. Thank you very much for your support. 🙏
1. Receive a request
Suppose we need a custom View class, which needs to implement different animation effects, including translation, rotation, scaling, etc. We can use the policy mode to implement this function so that each animation effect corresponds to a policy class.
2. Do not use policy mode
Need to be inAnimatedView
Implement all animation effects in the class
class AnimatedView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { var animationType: String = "translate" fun startAnimation() { when (animationType) { "translate" -> { // Implement flat-moving painting } "rotate" -> { // Implement rotation animation } "scale" -> { // Implement scaling animation } else -> { throw IllegalArgumentException("Invalid animation type") } } invalidate() } }
The call is as follows, and it needs to beAnimatedView
Set the animation type in the object and callstartAnimation
Method to start the animation:
{ animationType = "translate" }.startAnimation() animatedView().apply { animationType = "rotate" }.startAnimation()
In this implementation, if the animation effect needs to be added or modified, we need to modify itAnimatedView
Code in the class, which will increase the complexity of the code and maintenance cost.
3. Use the policy mode
When using the policy model, we only need to add or modify the policy implementation class, without modifying the existing code. Therefore, using policy patterns can better achieve the scalability and maintainability of the code.
we willAnimation
There are many ways to implement (different behaviors) and these behaviors are regarded as oneAnimationStrategy
Policy interface
Defines a strategy for applying animation
interface AnimationStrategy { fun applyAnimation(view: View) }
It is just an interface, waiting for the specific animation to be implemented, and the initial settings areanimationType
, the way to judge by if in onDraw
Modify to use the current policy object
private var animationStrategy: AnimationStrategy? = null
Called in onDraw
override fun onDraw(canvas: Canvas?) { (canvas) if (animationStrategy != null) { animationStrategy!!.applyAnimation(this) } }
Let's write a few other policy implementation classes that define different policy implementation classes, and these implementation classes implement themAnimationStrategy
Interface, and according to different needs, different policy implementation classes can be selected to apply different animation effects.
class TranslateAnimationStrategy : AnimationStrategy { override fun applyAnimation(view: View) { // Implement flat-moving painting } } class RotateAnimationStrategy : AnimationStrategy { override fun applyAnimation(view: View) { // Implement rotation animation } } class ScaleAnimationStrategy : AnimationStrategy { override fun applyAnimation(view: View) { // Implement scaling animation } }
The usage method is as follows: Choose different strategy implementation classes according to different needs
{ animationStrategy = TranslateAnimationStrategy() // Perform pan-moving painting //or animationStrategy = RotateAnimationStrategy() // Execute rotation animation //or animationStrategy = ScaleAnimationStrategy()// Execute zoom animation}
andAnimationStrategy
As a unified interface, the interface can enable different policy implementation classes to be used uniformly, thereby realizing the decoupling and scalability of the code.
Integrate
class AnimatedView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { var animationStrategy: AnimationStrategy? = null set(value) { field = value invalidate() } override fun onDraw(canvas: Canvas?) { (canvas) animationStrategy?.applyAnimation(this) } }
4. Summary
A policy pattern is a behavioral design pattern that allows the algorithm or behavior to be selected dynamically at runtime, so that the algorithm or behavior can vary independently of the client using them. Changes to animations in the examples do not require modificationAnimatedView
It is usually composed of one interface or abstract class and multiple implementation classes. The client executes algorithms or behaviors by calling methods in an interface or abstract class, while the specific implementation is done by the policy implementation class. In the example, AnimationStrategy is an interface and each animation is an implementation class.AnimatedView
passanimationStrategy?.applyAnimation(this)
To execute
In this way, we can also see
- A class needs to use different algorithms or behaviors at runtime according to different situations.
- A class defines many behaviors, and these behaviors appear in the form of multiple conditional statements in the class method. "Decomposing" these behaviors into different policy classes can avoid the complexity of conditional statements.
- Algorithms are not used very frequently, so they can be encapsulated into policy classes to avoid making the entire system bloated.
- Multiple classes only have slightly different algorithms or behaviors.
Using policy patterns can increase the flexibility and maintainability of the code, making the code easier to expand and modify. But don’t use it randomly, after all, there are many more categories, right?
Ending
Design patterns are a very wide topic, and many design patterns have extremely high similarity, which is easy to be confused when they are first exposed, so it is difficult to know which design pattern should be used under what circumstances. I will try my best to provide the design pattern case for the smallest unit encountered during development. Better understand when and how to use design patterns.
The above is the detailed content of the tutorial on learning the Strategy Pattern of Android Design Pattern in 5 minutes. For more information about the Strategy Pattern of Android Strategy Pattern, please follow my other related articles!