Strategy Pattern in Angular
Implementing Strategy Pattern in Angular is easy when we have good basics
Implementing design patterns in practical can be difficult. Recently I implemented a real use case of strategy pattern in Angular.
I was given a task of image file upload. I created a component and implemented as below.
Now the requirement changed. A flag was introduced and based on its value we will either compress the images or do not compress and then upload them.
A naive approach is to use simple branching like below:
This is what we currently see in the browser:
You can see, it violated ‘Open Closed design principal’, which states that “a class should be Open for extension and Closed for modification.”
One more change in requirement would introduce switch statement and the component code would increase. Also compression code is not responsibility of component[Violation of Single Responsibility Principal]. This should be delegated to some other class.
Now this is perfect case to introduce the strategy pattern. On the change of switch in HTML, strategy should change dynamically and accordingly, processing of files must be done.
So we will modify our code as below:
- Create Strategy abstract class with abstract
processFiles
method - Extend it to separate concrete strategy namely
StrategyWithCompression
andStrategyWithoutCompression
- Implement the method
processFiles
in concrete classes. - In component make following changes.
- Inject injector in constructor.
- Delete
processFiles
andprocessCompressedFiles
as this will be part of concrete classes. - Set default strategy on
ngOnInit
- Get strategy on toggle of switch from map.
Strategy Pattern implementation
Component code will look like as below:
You can find whole project on stackblitz on below link:
Thank you for reading this piece. I hope it has been useful!
I’ve created an Angular Course on Udemy which covers many practical problems and solutions in Angular including this one. It could be a stepping stone in your professional Angular Journey. Please take a look.
You can also watch/subscribe my free YouTube channel.
Please subscribe/follow/like/clap.
Build composable frontend and backend
Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.
Bring your team to Bit Cloud to host and collaborate on components together, and greatly speed up, scale, and standardize development as a team. Start with composable frontends like a Design System or Micro Frontends, or explore the composable backend. Give it a try →