Apply Design Patterns In Java (Part 1)
Nguyen Hai Dang (Eric)
? Software Engineer | Backend | Devops | Database Optimization | AWS Cloud | Azure Cloud | Java | Let's connect?
1. Overview
Design patterns are proven valuable solutions that serve as a model for solving design problem and may be used in a variety of situations to provide effective and efficient results. It also helps making your code readable and maintainable. Following are generally the design pattern categories:
Applying design patterns allows creating more maintainable, scalable, and reliable software.
2. Strategy Pattern
2.1 Definition
Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.
2.2 Problem
We have a class NotificationService like this:
In the initial design, NotificationService has a type field that determines how to send notifications. This approach has several drawbacks:
2.3 Solution
The Strategy Pattern refactors NotificationService to use a Notifier interface, which allows different notification strategies (e.g., SMSNotifier, EmailNotifier). This design:
2.4 Code Example
领英推荐
3. Factory Method Pattern
3.1 Definition
Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be?created.
3.2 Problem
In the initial design, the NotificationService directly depends on the Notifier interface, and specific notifier types like SMSNotifier and EmailNotifier are directly instantiated. This approach:
3.3 Solution
The Factory Method Pattern introduces an abstract NotifierCreator class with a createNotifier method. Subclasses (SMSNotifierCreator and EmailNotifierCreator) override this method to instantiate specific notifiers. This design:
3.4 Code Example
??Java Software Engineer | Oracle Certified Professional
8 个月Good to know !!
??Project Team Leader @ CNV Loyalty | Database Administrator | Problem Solving | Software Engineer
8 个月Good job!
?Student at Hanoi University | ReactJS | (.NET) | AI Tuner | Database Optimization | AWS | Azure?
8 个月Thanks for sharing