seon99il

Architecture

Factory Pattern without if-else

2 min read

What is Factory Pattern?

It defines an interface for creating objects and allows subclasses to decide which class to instantiate.

Pros and cons

  • Even if you don’t know in advance which class to create, the factory class takes care of creating the object.
  • The data type of an object is determined by its subclass → Ease of scalability
  • Minimizes redundancy

Why use Factory Pattern?

Because the basic principle of object-oriented design patterns is that they should be open for extension and closed for modification. (OCP, Open Closed Principle) It should be possible to extend or change the functionality of a module without modifying the code.

When to use Factory Pattern?

For the sake of abstraction, an interface or abstract class sometimes has multiple implementations. In this case, we use a factory class that finds out which implementation to use.

Example

There are two types of coupons: point accumulation coupons and stamp accumulation coupons.

ServiceImpl must be called according to the requested coupon type.

CouponType

In this case you can use a factory class like this.

ServiceFactory

Then the controller uses the service factory to find and use the implementation. But a few problems arise in this case. You will need to modify your factory class if you have a new couponType.

ServiceFactory

Maintenance will be difficult and the OCP principle will be violated.

  • OCP: (Open-Closed Principle) Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.

Problem solving

Implement it so that the factory class does not change when services are added.

PointCouponServiceImpl

Create a method that returns true or false using CouponType.

The factory class is implemented like this:

ServiceFactory

If there are multiple implementations, you can receive them as a List.

CouponController

This way you don’t have to modify the FactoryClass every time a new coupon service is added.

Using caching

The above behaves inefficiently when there are many identical requests.

It first scans memory to find an implementation, and if it doesn’t find one, it searches the full list.

ServiceFactory

  1. Find the service in Map<CouponType, CouponService>
  2. If a service is found, return service
  3. If there is no matching service in couponFactoryCache, find it in the full list of coupon services, put it into couponFactoryCache, and return the service

Previous posts

View all posts →

Comments